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
});
});
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…