Home > Mobile >  Invalid Hook Call for custom hook
Invalid Hook Call for custom hook

Time:09-19

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

CodePudding user response:

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

CodePudding user response:

Hooks can't be used inside handler functions.

Do this instead:

import { FetchData } from './FetchData'

export const MainPage = props => {
    const {fetchData, setFetchData} = FetchData(url, query, variable)
    const onClick = (event) => {
         console.log(fetchData)
    }
}
  • Related