I want to make a Logout function when the token has expired. There is an AuthProvider
in my application:
const AuthContext = createContext({});
export const AuthProvider = ({ children }) => {
const [auth, setAuth] = useState({ token: localStorage.getItem("access_token") });
return (
<AuthContext.Provider value={{ auth, setAuth }}>
{children}
</AuthContext.Provider>
)
}
export default AuthContext;
Now that the token has expired I need to call the setAuth
hook and write an empty token there:
const logout = () =>{
const axiosInstance = axios.create({
withCredentials: true
})
axiosInstance.get("http://localhost:8080/api/auth/logout")
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error.config);
});
window.location.href = '/auth'
};
const Logout = () => {
const {auth,setAuth} = useAuth();
const token = '';
setAuth({token});
localStorage.removeItem("access_token");
localStorage.clear();
logout()
};
export default Logout;
I am exporting this function in another file and want to call if the backend returns a response about an expired token.
const getStockData = async () => {
return instance.get(`/api/stock/symbols/${slug}`);
}
useEffect(() => {
(async () => {
const response = await getStockData();
console.log(response)
const data = response.data;
const stockInfo = data.chart.result[0];
console.log(stockInfo);
setPrice(stockInfo.meta.regularMarketPrice.toFixed(2));
setPriceTime(new Date(stockInfo.meta.regularMarketTime * 1000));
setSymbol(stockInfo.meta.symbol);
const quote = stockInfo.indicators.quote[0];
const prices = stockInfo.timestamp.map((timestamp, index) => ({
x: new Date(timestamp * 1000),
y: [quote.open[index], quote.high[index], quote.low[index], quote.close[index]].map(round)
}));
setPriceInfo([{
data: prices,
}]);
setStockData({ data });
})().catch(
(error) =>{
Logout()
}
);
}, []);
Here getStockData can return 403 if the token has expired.
But of course I get an error saying that the hook can't be used in a function like that. And I can't find a solution how to wrap or to do something similar so that this function can be called?
CodePudding user response:
React doesn't let you initialize hooks inside of non-component functions. Instead, you can initialize the hook on the component level and let whatever function needs the hook's values to accept them as arguments.
const Logout = (auth, setAuth) => {
const token = '';
setAuth({token});
localStorage.removeItem("access_token");
localStorage.clear();
logout()
};
export default Logout;
// Initialize the hook at the component level
const {auth, setAuth} = useAuth();
.catch(
(error) =>{
// then pass the values from above to this function
Logout(auth, setAuth)
}
);