Its a action-function that works with redax (it works perfectly because I used it)
export const fetchCategory = () => {
return async (dispatch) => {
try {
dispatch(settingsSlice.actions.settingsFetching());
const response = await request("/category/getAll", "POST", {});
dispatch(settingsSlice.actions.settingsFetchingSuccess(response));
} catch (e) {
dispatch(settingsSlice.actions.settingsFetchingError(e));
}
};
};
I need that when the button is pressed, a request is made to the server and the state is updated
Here is the function that is executed when you click on the button :
const buttonHandler = async () => {
await request("/category/create", "POST", {
newCategory: {
label: form.categoryLabel,
limit: form.categoryLimit,
},
});
setForm(initialState);
fetchCategory();
};
I checked, the form is sent to the backend and everything works fine except for this "fetchCategory"
I already tried to do this using useEffect
useEffect(() => {
fetchCategory();
}, [Button , buttonHandler]);
i tried to install different dependencies but no result. How can this problem be fixed?
>Solution :
You need to dispatch the action!
Your fetchCategory function is a "thunk action creator". Calling fetchCategory() creates the thunk action, but doesn’t do anything with it. You need to call dispatch(fetchCategory()) to execute the action.
const buttonHandler = async () => {
await request("/category/create", "POST", {
newCategory: {
label: form.categoryLabel,
limit: form.categoryLimit,
},
});
setForm(initialState);
--> dispatch(fetchCategory()); <--
};