I am using Redux and Apollo Client in my project. I would like to dispatch an action to trigger a message bar on top, stating the session is expired, when GraphQL endpoint returns 401 (Session expired).
But the client object is not an component, I cannot use useDispatch here, is there any way I can dispatch an action in onError?
import { InMemoryCache } from "apollo-cache-inmemory";
import ApolloClient from "apollo-client";
import { onError } from "apollo-link-error";
import { HttpLink } from "apollo-link-http";
const customFetch = (uri, options) => {
return fetch(uri, options)
.then(response => {
console.log("response fetch", response)
switch (response.status) {
case 400:
case 401:
case 500:
case 504:
return Promise.reject(response);
default:
return response;
}
});
};
const requestLink = new HttpLink({
uri: "/graphql",
fetch: customFetch,
});
const errorLink = onError(({ graphQLErrors, networkError, response }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, extensions }) => {
console.log(`[GraphQL error]: Message: ${message}, Location: ${extensions.code}`);
});
if (networkError) {
// TODO: Dispatch error to trigger a message bar component appear
console.log("[GraphQL networkError], ", networkError);
}
});
const link = errorLink.concat(requestLink);
const client = new ApolloClient({
link: errorLink.concat(requestLink),
cache: new InMemoryCache({
addTypename: false,
}),
});
export default client;