This is a similar question but it provided solution for the specific issue of OP
I am trying to implement authentication in my React app using JWT
. After logging in, server sends access token
and refresh token
. Access token expires shorty within an hour while refresh token is persistant for a year. Both are stored in localStorage
.
I am using axios
to make requests to server. I have created a file api.js
that creates an axiosInstance
which sets up baseURL for requests. This file exports this axios instance and every other component/ file that wants to use axios, imports it from this file - api.js. I have also set up an axios interceptor
in the same file that will modify each request before sending it. It will basically add access token in authorization
header if token has not expired, otherwise it will use refresh token to get new access token.
Now I have a TokenProvider
Context that basically wraps whole app and it gives you token and a method to update this given token as well as the one in localstorage (useToken)
.
After i get the access token from the server with the help of refresh token, i want to update it in localstorage as well as the token that TokenProvider provides. I tried importing useToken from TokenProvider in api.js but React won't allow to use hooks in functions that are not components.
React Hook "useToken" is called in function "{functionName}" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter.
How should i go about implementing this functionality to update TokenProvider's token? Should i listen for events in TokenProvider that are trigged when localStorage updates or shoudl i try to convert api.js into some type of React component?