My app needs a specific header value from the response header, on error. I couldn’t find a good solution for this. Right now, I use context
to set a callback (in useQuery), and access it inside onError
(as below).
This requires every useQuery/useMutation call to set this context with callback and I’m wondering if there is a better way. e.g. if useQuery could provide context in response?
const callbackHandler = (operation: Operation) => {
const fetchResponse = get(operation.getContext(), 'response');
const fetchRequest = get(operation.getContext(), 'request');
const { headers } = fetchResponse || fetchRequest;
const headerVal = headers.get(HEADER_NAME);
const callback: (t: string) => void = get(operation.getContext(), 'headerValCallback');
if (callback) {
callback(headerVal);
}
};
const errorLink = (errorResponse: ErrorResponse) => {
const { networkError, operation } = errorResponse;
const statusCode = get(networkError, 'statusCode');
callbackHandler(operation);
};
// link passed to Apollo client
const link = onError(errorLink);
// then in useQuery
const result = useQuery(query, {
...options,
context: { headerValCallback },
});