I'm trying to figure out how to set an initial state for a store in redux. I'm using https://github.com/reactjs/redux/blob/master/examples/todos-with-undo/reducers/index.js as an example. I tried to modify the code such that the todos had a value initialized.
const todoApp = combineReducers({ todos, visibilityFilter }, { todos: [{id:123, text:'hello', completed: false}] })
following the doc: http://redux.js.org/docs/api/createStore.html
but it's not working, and I'm not quite sure why.
A state in Redux is a JavaScript object, where the internal state of the application is stored as its properties, e.g. which user is logged on. After having logged in, the user of your application may navigate to different pages in your application, but you need to remember somehow, who that user is.
Initializing state In class components, there are two ways to initialize state — in a constructor function or as a Class property. Constructor functions, introduced in ES6, is the first function called in a class when it is first instantiated — meaning when a new object is created from the class.
One way to do that would be to write a root reducer in your application. The root reducer would normally delegate handling the action to the reducer generated by combineReducers() . However, whenever it receives USER_LOGOUT action, it returns the initial state all over again.
Redux restricts updating the state to this method only. This strict way of updating the state ensures that the state can not be changed directly either by view or any network callback. The only way to update a state is by defining the action and then dispatching it. Remember that actions are plain JavaScript objects.
It needs to be the second argument to createStore
:
const rootReducer = combineReducers({ todos: todos, visibilityFilter: visibilityFilter }); const initialState = { todos: [{id:123, text:'hello', completed: false}] }; const store = createStore( rootReducer, initialState );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With