Parkicism
Parkicism

Reputation: 2535

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, data/articles.js that creates a default state in store.js.

Thanks

Upvotes: 4

Views: 5452

Answers (2)

Alexandr Subbotin
Alexandr Subbotin

Reputation: 1734

I also had this problem. It turned out that you have to add a lot of code for this simple task. So I simplified this process and created a package for async loading of initial state in redux - redux-async-initial-state.

You can check out examples and in your case in the end your store creator will look like this:

// Load initial state function
const loadStore = () => {
  return Promise(resolve => {
    fetch('/data/articles.js')
      .then(response => response.json())
      .then(resolve);
  });
}

const storeCreator = applyMiddleware(asyncInitialState.middleware(loadStore));
const store = storeCreator(reducer);

Upvotes: 1

MariuszJasinski
MariuszJasinski

Reputation: 504

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 :)

Upvotes: 4

Related Questions