jasonetco
jasonetco

Reputation: 356

defaultState of Redux store from API

How can I make the default state of my Redux store be data that comes in from an API request?

I want to make a request like this, then pass that returned data as the defaultState when creating the store:

const request = new XMLHttpRequest();
request.open('GET', '/api', true);
request.onload = function load() {
  if (this.status >= 200 && this.status < 400) {
    const data = JSON.parse(this.response);
  } else {
    // We reached our target server, but it returned an error
  }
};


const store = createStore(rootReducer, defaultState, enhancers);

Upvotes: 0

Views: 474

Answers (1)

Maciek Jurczyk
Maciek Jurczyk

Reputation: 575

If you'd like to set an asynchronously loaded state as a default, you should try loading it before starting the application in index.js:

import reducer from './reducer';

function asyncStateLoadingFunction(callback) {
  const request = new XMLHttpRequest();
  request.open('GET', '/api', true);
  request.onload = function load() {
    if (this.status >= 200 && this.status < 400) {
      callback(JSON.parse(this.response));
    } else {
      callback(null, 'Error occured');
    }
  };
};

Promise((resolve, reject) => {
  asyncStateLoadingFunction((result) => {
    resolve(result);
  }, (error) => {
    throw new Error(error);
  });
})
.then((initialState) => {
  // NOTE Create the Redux store, routers etc now
  const store = createStore(reducer, initialState);

  ReactDOM.render(
    <Provider store={store}>
      <App />
    </Provider>,
    document.querySelector('#app')
  );
});

Upvotes: 1

Related Questions