Reputation: 2230
I am basically trying to create a react webapp with lot of pages. And the data for each page is loaded through different API calls. And most response have information dependent on each other. I decided to use redux to store these response and access from each components.
This is what my reducer file look like,
var initialState = {
"userDetails": [],
"userPicks": []
};
module.exports = function(state, action, data) {
state = state || initialState;
switch (action.type) {
case 'ADD_USER_LIST':
return Object.assign({}, state, {
"userDetails": action.data
})
case 'ADD_USER_PICK_LIST':
return Object.assign({}, state, {
"userPicks": action.data
})
case 'UPDATE_SELECTION':
return Object.assign({}, state, {
return "do something"
});
default:
return state
}
}
So I use
var redux = require('redux');
var reducers = require('./reducers');
var store = redux.createStore(reducers);
on top of each component that uses information from store.
store.getState()
but this process always resets my reducer state to initial one and the app loses all data. Can anyone point out where I am wrong and what I should be looking in to?
Upvotes: 0
Views: 857
Reputation: 6803
You have to create redux store once in your toplevel app
var redux = require('redux');
var reducers = require('./reducers');
var store = redux.createStore(reducers);
Dont create for every compnent. Use container components to mapStatetoProps and mapDispatchToProps and pass props to the components
Upvotes: 1
Reputation: 45121
"Can anyone point out where I am wrong " you are creating new store for every component type. You need to make it a separate module and create store once per application.
// redux/store js
var redux = require('redux');
var reducers = require('./reducers');
module.exports = redux.createStore(reducers);
"what I should be looking in to" you should take a look at official react binding for redux. React Redux.
// app.js
var store = require('./redux/store.js');
var Provider = require('react-redux').Provider
ReactDOM.render(
(<Provider store={store}>
<App />
</Provider
), mountingPoint)
Upvotes: 3