Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

javascript - How to wait for data to be loaded before calling getState() in redux

I have an action, userAction, that will call an API to load data from the database, and I want to use that data within a separate action, calcAction, so that I can post to an API with the data from userAction but when I call getState() in calcAction I get the initial state. How do I make sure that getState() will only get the state once the userAction has loaded the data from the database?

My calcReducer looks like this:

export const getAllCharReq = () => (dispatch, getState) => {
  const { userData } = getState();
  axios.post('/api/character', userData).then((res) => {
    dispatch({
      type: GET_ALL_CHAR_REQ,
      payload: res.data,
    });
  });
};

The userAction is called in the app component so that it loads the user data when first accessing the website. And the calcAction is called in componentDidMount() of a child component so that I can get the relevant data only when the component is accessed. So this is only a problem if a user loads this child component first. If a user were to navigate to this child component then the userData is loaded.

question from:https://stackoverflow.com/questions/65835354/how-to-wait-for-data-to-be-loaded-before-calling-getstate-in-redux

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can handle it inside of your thunk by executing the fetch only when the userData is present.

export const getAllCharReq = () => (dispatch, getState) => {
  const { userData } = getState();
  if (userData) {
    axios.post("/api/character", userData).then((res) => {
      dispatch({
        type: GET_ALL_CHAR_REQ,
        payload: res.data
      });
    });
  } else {
    dispatch({
      type: "ERROR",
      payload: "No user data found"
    });
  }
};

You can also pass the userData from your component as an argument to the action creator, which is what I would recommend if it's doable with your app structure. Within the component, you would know not to dispatch the thunk unless the userData is loaded.

export const getAllCharReq = (userData) => (dispatch) => {
  axios.post("/api/character", userData).then((res) => {
    dispatch({
      type: GET_ALL_CHAR_REQ,
      payload: res.data
    });
  });
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...