[SOLVED] Invalid Hook Call for custom hook

Issue

This Content is from Stack Overflow. Question asked by Devil’s Dream

I have written a function for API calls. I want to reuse this function from a different page.

FetchData.js

export const FetchData = (url, query, variable) => {
    const [fetchData, setFetchData] = useState([]);

    useEffect(() => {
        const fetchData = async () => {
            const queryResult = await axios.post(
                url, {
                query: query,
                variables: variable
            }
            )
            const result = queryResult.data.data;
            setFetchData(result.mydata)
        };

        fetchData();
    })

    return {fetchData, setFetchData}

}

Here is my main page from where I am trying to call the API using the following code

mainPage.js

import { FetchData } from './FetchData'

export const MainPage = props => {

    const onClick = (event) => {
        const {fetchData, setFetchData} = FetchData(url, query, variable)
        console.log(fetchData)
    }
}

It is returning the following error –

Uncaught Error: 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

Solution

If you need to fetch data on response to an event, you don’t need a useEffect.

const useData = (url, query, variable) => {
  const [data, setData] = useState([]);
  const fetchData = async () => {
    const queryResult = await axios.post(url, {
      query: query,
      variables: variable,
    });
    setData(queryResult.data.data);
  };
  
  return {data, fetchData}
};

export const MainPage = (props) => {
  const {data, fetchData} = useData(url, query, variable);
  const onClick = (event) => {
    fetchData()
  };
};

Answered by Reifocs

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5.CC BY-SA 3.0.CC BY-SA 4.0.

people found this article helpful. What about you?