search

Home  >  Q&A  >  body text

The dispatch function has no effect after pressing the button

This is an action function for use with redax (it works perfectly since 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));
    }
  };
};

When the button is pressed, I need to make a request to the server and update the status

This is the function that executes when you click the button:

const buttonHandler = async () => {
    await request("/category/create", "POST", {
      newCategory: {
        label: form.categoryLabel,
        limit: form.categoryLimit,
      },
    });
    setForm(initialState);
    fetchCategory();
  };

I've checked, the form has been sent to the backend and everything is fine except "fetchCategory"

I have tried using useEffect to solve this problem

useEffect(() => {
    fetchCategory();
  }, [Button , buttonHandler]);

I tried installing different dependencies but with no results. how to solve this problem?

P粉410239819P粉410239819441 days ago448

reply all(1)I'll reply

  • P粉704196697

    P粉7041966972023-09-17 14:40:47

    You need dispatch this action!

    Your fetchCategory function is a "thunk action creator". Calling fetchCategory() creates a thunk action but does nothing with it. You need to call dispatch(fetchCategory()) to perform this action.

    const buttonHandler = async () => {
        await request("/category/create", "POST", {
          newCategory: {
            label: form.categoryLabel,
            limit: form.categoryLimit,
          },
        });
        setForm(initialState);
    --> dispatch(fetchCategory()); <--
    };

    reply
    0
  • Cancelreply