P
P
Pogran2016-08-17 13:09:34
React
Pogran, 2016-08-17 13:09:34

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) => {

And now I want to upload data from the url localhost:3000/entities to initialState . How can I do it right. I saw that it is possible like this axios.get(`${apiPrefix}/entities`) , and then I don’t know how to pick them up and pass them to a variable

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Gushchin, 2016-08-17
@Pogran

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)

And in loadInitialData already load data via ajax, for example:
function loadInitialData() {
  return dispatch => axios
    .get(`${apiPrefix}/entities`)
    .then(entities => dispatch(saveEntities(entities)))
}

The example is very general, but the essence, I hope, is clear.
PS don't forget thunk middleware

K
Konstantin Gromov, 2016-08-17
@Pathgk

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 question

Ask a Question

731 491 924 answers to any question