Similiar to Should we use axios inside both components and store?
I have a state called authorization
which contains the Bearer token
value that would be used in Axios calls. The state is available in a context and accessible using the useContext
hook.
I create the AxiosInstance
where I add a interceptors.request.use
to add the Authorization
header.
What I've done so far was useMemo
with the authorization
value a a dependency. But since Axios operation is asynchronous it seems that I may get the wrong axios instance.
I did a bit of refactoring using useRef
and I still had a bit of an issue.
What I then did was implement the Observer pattern and send a notification to the component that provides the Axios client that the authorization header was changed and update the ref. However, again there's still some cases where the old client is being invoked.
What I am wondering is should I store it in useState
or is there a fundamental problem with the approach of storing the Axios client and instead should I just bite the bullet and create a new axios client per request which takes the authorization header that's presently in the state?