Anyone know how to set the state here?

Tell us what’s happening:

Your code so far


const INCREMENT = 'INCREMENT'; // define a constant for increment action types
const DECREMENT = 'DECREMENT'; // define a constant for decrement action types
const defaultState = {
state:0
};

const counterReducer = (state = defaultState,action) => {
switch(action.type){
 
  case 'INCREMENT':
  return {
    state : state++
  }

   case 'DECREMENT':
  return {
    state : state--
  }
}
}; // define the counter reducer which will increment or decrement the state based on the action it receives

const incAction = () => {
return {
  type:INCREMENT
}; // define an action creator for incrementing
}
const decAction = () => {
return {
  type:DECREMENT
}
}; // define an action creator for decrementing

const store = Redux.createStore(counterReducer); // define the Redux store here, passing in your reducers
console.log(store.getState())

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36.

Challenge: Write a Counter with Redux

Link to the challenge:

State can be primitive value, not necessarily the object. In fact, considering immutability of primitive values it is highly recommended in this case!

HI snigo

changed defaultState = 0;

still console.log(store.getState()) is / /undefined

When this runs, Redux passes the first system action of type “INIT”, it looks like your reducer isn’t quite prepared for such action. To fix it you need to include default case inside your switch statement.

Also, if you’ve changed default state, then you probably need to make corresponding changes in your reducer, because right now it returns object, not primitive value.

is there any need to dispatching the action to store?
store.dispatch(action())

No, what happens is when you create store, Redux will run your reducer once given this argument: { type: 'INIT' }. If you try to run it manually it will return undefined and this is what the new state will be and what console.log(store.getState()) will give you. You need to “account” for any actions of undefined types and return same state if they occur

1 Like