Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The function (dispath) does not work when I press the button

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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()); <--
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading