I created an API on my server to generate a JWT Token for the Apple WeatherKit API. I would like to use this token in my React SPA. I am using Redux Toolkit with createAPI
to connect to my server backend.
My implementation of createAPI
looks something like this:
export const generalApi = createApi({
reducerPath: 'api',
tagTypes: [ 'settings' ],
baseQuery: fetchBaseQuery({
baseUrl: 'https://api.myserver.com/v1/',
prepareHeaders: (headers, { getState })=> {
const token = getState().session.token;
if (token) {
headers.set('authorization', `Bearer ${token}`);
}
return headers;
}
}),
endpoints: (builder)=> ({
getWeatherKitToken: builder.query({
query: ()=> 'getWeatherKitToken',
forceRefetch: ({ endpointState })=> {
console.log('checking for refetch');
return (endpointState.data.expires < Date.now());
},
providesTags: [ 'settings' ]
}),
login: builder.mutation({
query: (body)=> ({
url: 'login',
method: 'POST',
body: body
}),
invalidatesTags: [ 'settings' ]
}),
}),
});
And is used like this:
const { data } = useGetWeatherKitTokenQuery();
I would expect my token to be automatically refetched when either the user logs in (and tags 'settings' get invalidated, or when the expirationtime of the token passed (this is provided by the API). I know there are different option to refetch on component mount or on focus or something, though I would only require a refetch when the token expired or the user session changed.
However, on neither initial component mount or component re-mount the forceRefetch
function is called. Am I understanding the implementation wrong or is there a better way to implement the desired behavior of the automatic refetching of expired tokens?
The best answer I came up so far is by adding a pollingInterval
of the same duration as the expirationTime. This is not exactly what I was looking for though quite close to it already.
More Information: https://redux-toolkit.js.org/rtk-query/usage/polling