0

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.
1
  • 1
    const [res, error] = useFetch('get', api + "/latest/" + num, {}); this is an invalid call. Hook can be called inside of the body of a function component. So don't call in your async function getThings. Commented Apr 25, 2022 at 14:10

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.