Home > Mobile >  How can I use custom hooks in react redux actions
How can I use custom hooks in react redux actions

Time:04-26

What I'm trying to do here is to simplify the code using hooks

Here is the action file

export const getThings = (num) => async dispatch => {
    dispatch({ type: constants.GET_HOME_PAGE_REQ });
    const [res, error] = useFetch('get', api   "/latest/"   num, {});
    useEffect(() => {
        res && dispatch({
            type: constants.GET_HOME_PAGE_RES,
            status: res.status,
            payload: res.data.message,
        });
    }, [res, dispatch]);
    useEffect(() => {
        error && dispatch({
            type: constants.GET_HOME_PAGE_ERROR,
            message: error.message,
            status: error.status,
        });
    } , [error, dispatch]);
};

and the error I'm getting

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app See for tips about how to debug and fix this problem.

CodePudding user response:

The purpose of React hooks (and custom hooks) is to manage the state and the lifecycle of React functional components. So it doesn't make sense to use it outside a react component and you are not allowed to do so, therefore the console error. If you just want to fetch some data from an API, create a variable like this:

const result = await fetch(...)

Docs: https://reactjs.org/docs/hooks-intro.html

CodePudding user response:

Use the react hooks like useEffect, useFetch inside a body of a function based component.it cannot be used inside normal javascript functions, u have used it in the return portion of that function.

  • Related