How to load inline dataset using ajax call in React redux?

I am having a problem with redux trying to load source data with an asynchronous call to my backend API that returns JSON. Right now, I'm trying to load a bunch of different articles, but I have no idea how to download it asynchronously. Since this is an initial dataset, should it be downloaded synchronously? If so, how do I get a synchronous call to my API? If not, how would I decide to solve this problem asynchronously?

I now have static json data data/articles.js, which creates the default state in store.js.

thank

+4
source share
2 answers

redux-thunk , fetch () .

: 1) , , :

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​​strong > - , , :

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

, , .

( ), fetchData​​strong > componentDidMount ( :)).

, , Example.

:)

+4

. , . redux - redux-async-initial-state.

, :

// 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);
+1

All Articles