user10265865
user10265865

Reputation: 179

How to set Redux Reducer's initial state based on AJAX call?

Using Redux, I want one of my reducers initial state to be based on an AJAX call. Basically, I am using AJAX to get some data, and then putting it into the state of the Reducer. However, because of the AJAX call, the reducer is initialized with the initial state before the AJAX call is complete. How would you go about making reducer wait until the AJAX call is complete before setting the initial state?

STORE

export default () => {
  const store = createStore(
    combineReducers({
      settings: settingsReducer,
    })
  );
  return store;
}

REDUCER

var settingsDefaultState;

$.ajax({
  url: 'view/content/settings.xml',
  type: 'GET',
  success: function(xml) {
    //DOING SOME STUFF WITH THE XML FILE HERE
    settingsDefaultState = {
      test: "HELLO WORLD"
    }
  },
  complete: function() {
    console.log("Settings Loaded...");
  }
});


export default (state, action) => {
  var tempState = {...state};
  switch (action.type) {
    default:
      return tempState;
  }
}

Upvotes: 0

Views: 503

Answers (1)

rubentd
rubentd

Reputation: 1275

I suggest you initialize your state as a loading state. That way you can give feedback to the user that something is happening. Then when the ajax call returns a response you trigger an action that will set your state to the desired next state.

Upvotes: 1

Related Questions