Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set initial state in redux

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.

like image 598
Saad Avatar asked Jun 14 '16 22:06

Saad


People also ask

How do you define a state in Redux?

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.

How do you initialize a state?

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.

How do you reset reducer state to initial state?

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.

Can we change Redux state directly?

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.


1 Answers

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 ); 
like image 189
ctrlplusb Avatar answered Sep 26 '22 02:09

ctrlplusb