Parkicism Parkicism - 1 year ago 164
React JSX Question

How do I load inital set of data with ajax call in React redux?

I have a problem with redux trying to load initial data with an asynchronous call to my backend API that returns a JSON. Right now, I'm trying to load a bunch of different articles, but I have no idea how to load it asynchronously. Since it is an initial set of data, should I load it synchronously? If yes, then how would I acheive a synchronous call to my API? If not, how would I go about solving this problem asynchronously?

Right now, I have static json data,

that creates a default state in


Answer Source

You should use a redux-thunk middleware, which allows you to dispatch async actions and a fetch library (for example) for downloading your initial data.

So: 1) create an action which fetch your data, example:

export function fetchData() {
  const options = {
    method: 'GET',
    headers: {
      'Authorization': 'Client-ID xx' // if theres any needed

  return (dispatch) => {
    return fetch('yourUrl.json', options)
      .then(response => response.json())
      .then(data => dispatch(receiveYourData(data)))
      .catch(err => console.log(err));

receiveYourData is a action which will place your data in your state, example:

export function receiveYourData (payload = []) {
  return {
    type: RECEIVE_DATA,
    payload: payload

Of course you have to write action handler, which after dispatching an action, will place your data in your state.

If you have your setup (similar to above), you should dispatch fetchData in your componentDidMount lifecycle method (its one of the option of course :) ).

If you dont know how to do particular parts, you can refer to this Example.

Also official async example may be helpful :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download