i have a axios config file, and i call react hook {Auth Context} in that file with the purpose to fetch the token in react context api. but i got an error like this "React Hook 'useAuth' cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function"
AuthContext.js
import React, { useContext, createContext, useState } from "react";
const AuthContext = createContext();
export function useAuth() {
return useContext(AuthContext);
}
export function AuthProvider({ children }) {
const [currentToken, setCurrentToken] = useState("");
const [isAuth, setIsAuth] = useState(false);
function login(token) {
setCurrentToken(token);
setIsAuth(true);
}
const value = {
login,
currentToken,
isAuth,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
and my axios config file something like this
AxiosConfig.js
import axios from "axios";
import { useAuth } from "./AuthContext";
const { currentToken } = useAuth(); //my Reeact Context
export default axios.create({
baseURL: "http://127.0.0.1:8000",
headers: {
"Content-type": "application/json",
Authorization: `Bearer ${currentToken}`,
},
});
what is the best way to achieve that goal ?
Thank you in advance
CodePudding user response:
Hooks were not meant to be used outside of a component, and useContext
and useAuth
(which uses useContext
) is a hook. Here's a quote from freecodecamp:
You can not use hooks outside a component function, it is simply how they work. But, you can make a composition of hooks. React relies on an amount and order of how hooks appear in the component function. So don't even think of wrapping those calls with conditional logic of some sort.
As you read above, you are not supposed to do this in react applications.
CodePudding user response:
you can create an api and set the token when it's needed, since your api is the same throughout the code, this will work.
const api = axios.create({
baseURL: process.env.NEXT_PUBLIC_END_POINT,
});
export const setApiToken = (token: string) => {
api.defaults.headers.common["Authorization"] = `bearer ${token}`;
};