I am using urql GraphQL client in my project. After I log in, it's not adding a token in the authorization header automatically, as it should. I have to refresh the page once and then the token is set in the header. I have been through the documentation and can't seem to figure out what I am doing wrong.
Here is my implementation :
export const urqlClient = createClient({
url: `${url}`,
exchanges: [
dedupExchange,
cacheExchange,
authExchange({
getAuth: async ({ authState, mutate }: any) => {
// for initial launch, fetch the auth state from storage (local storage, async storage etc)
const token = Cookies.get('token');
if (!authState) {
if (token) {
return { token };
}
return null;
}
// refresh token
const decoded = jwt_decode<MyToken>(token as any);
if (typeof decoded.exp !== 'undefined' && decoded.exp < Date.now() / 1000) {
const user = firebase.auth().currentUser;
if (user) {
await user.getIdToken();
}
}
//auth has gone wrong. Clean up and redirect to a login page
Cookies.remove('token');
await signOut();
},
addAuthToOperation: ({ authState, operation }: any) => {
// the token isn't in the auth state, return the operation without changes
if (!authState || !authState.token) {
return operation;
}
// fetchOptions can be a function (See Client API) but you can simplify this based on usage
const fetchOptions =
typeof operation.context.fetchOptions === 'function'
? operation.context.fetchOptions()
: operation.context.fetchOptions || {};
return makeOperation(operation.kind, operation, {
...operation.context,
fetchOptions: {
...fetchOptions,
headers: {
...fetchOptions.headers,
Authorization: `Bearer ${authState.token}`,
},
},
});
},
}),
fetchExchange,
]
});
What am I doing wrong here? Thanks