How to avoid error : Invalid hook call. Hooks can only be called inside of the body of a function component?

I have separate file where I do my get and post axios calls . So in this file I have this code

  import { useSelector, useDispatch } from "react-redux";
  import __ from 'lodash'
  import axios from "axios";
  import { getPersistedToken } from "src";
  import { PROCESS_STATUS } from "src/model";


  export const getAxiosQuery = (endpoint) => async () => {
    const dispatch = useDispatch()
    console.log(dispatch)

     return await axios.get(endpoint, {
       headers: {
       'Authorization': 'Bearer ' + getPersistedToken(),
      }
   }).then((res) => {
   dispatch(processStatusAction(PROCESS_STATUS.DONE))
   return res
   },
  ).catch(error => {
  dispatch(processStatusAction(PROCESS_STATUS.FAIL))
 });
}

Is there any way please to allow using react hooks in my function ? because I won’t pass dispatch variable in parametres of this function in all my calls

Answer

Is there any way please to allow using react hooks in my function ? because I won’t pass dispatch variable in parametres of this function in all my calls

No, there’s no way that you can use a hook in your function. You can only use hooks in (functional) React components. Information here.

What you can do in your case, is create a custom hook (say useAxiosQuery) which retrieves the dispatch function and automatically injects it, such as:

const useAxiosQuery = (endpoint) => {
  const dispatch = useDispatch();
  
  return getAxiosQuery(endpoint, dispatch);
}