I am trying to make a custom usefetcher in my Nextjs18 typescript project but it keeps giving me the "Invalid hook call. Hooks can only be called inside of the body of a function component." error. Here is the code:
and I get the error
I have "@types/react": "^18.0.26", "@types/react-dom": "^18.0.9", "react": "18.2.0", "react-dom": "18.2.0", but I also tried deleting node_modules and yarn.lock and running npm script for installing the latest versions which didn't work.
JavaScript:
import { Axios as request } from "./axios";
import { AxiosRequestConfig } from "axios";
import { useContext } from "react";
import { UserContext } from "../../context";
interface IConfig extends AxiosRequestConfig {
useToken?: boolean;
formData?: boolean;
}
export const UseFetcher = <T, G = any>(config: IConfig) => {
const axiosConfig: AxiosRequestConfig = config;
//token and user data
const {state: userState} = useContext(UserContext);
//header config
axiosConfig.headers = {
...axiosConfig.headers,
accept: "application/json",
"x-http-request-details": "app-version-code=1;platform=0;",
appversion: "1",
"Content-Type": config?.formData
? "multipart/form-data"
: "application/json;charset=UTF-8",
...(config.useToken
? { Authorization: `Bearer ${userState?.tokens?.access}` }
: null),
};
return (data?: G) =>
new Promise<T>((resolve, reject) => {
if (data) axiosConfig.data = data;
if (data && axiosConfig.method === "GET") axiosConfig.params = data;
//send request
return request(axiosConfig)
.then((res) => {
//handle success
if (res?.data?.isSuccess) resolve(res?.data);
else {
//handleFailedRequest(res as any);
//reject(res?.data);
// handleFailedRequest(res)
}
})
.catch((error) => {
//handle unsuccess
//handleFailedRequest(error);
//reject(error?.response?.data);
});
});
};
Unhandled Runtime Error
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 See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.I have "@types/react": "^18.0.26", "@types/react-dom": "^18.0.9", "react": "18.2.0", "react-dom": "18.2.0", but I also tried deleting node_modules and yarn.lock and running npm script for installing the latest versions which didn't work.