Reputation: 1
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.
Upvotes: 0
Views: 688
Reputation: 42258
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
});
});
};
Upvotes: 0