Answer the question
In order to leave comments, you need to log in
How to get data via request?
I have a server side and a client side. on the server side, I have a route localhost:3000/entities in which json data from the mongo database prntscr.com/c6sf8e . When initializing the application, I want to load this data in reducers, like this
const initialState = [
{
id: 0,
text: 'Product',
active: 0,
selected: 0
}
];
const entities = (state = initialState, action) => {
Answer the question
In order to leave comments, you need to log in
Make an action that will be responsible for loading the initial data. The loading itself should take place not at the time of creating the reducers, but at the start of the application. For example like this:
const store = createStore(history, client, initialState)
store.dispatch(appActions.loadInitialData())
render((
<Provider store={store}>
<Router history={finalHistory}>
{routes}
</Router>
</Provider>
), reactRootElement)
function loadInitialData() {
return dispatch => axios
.get(`${apiPrefix}/entities`)
.then(entities => dispatch(saveEntities(entities)))
}
createStore takes the start state as the second argument just for such cases. The code will look something like this:
axios.get(`{apiPrefix}/entities`).then(initState => {
const store = createStore(reducer, initState);
// код использующий store
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question