const customFetch = async ( uri: RequestInfo, options: RequestInit | undefined ) => { const response = await fetch(uri, options); const bodyJson = await response.json(); if ( bodyJson && bodyJson.errors && bodyJson.errors[0] && bodyJson.errors[0].message === 'Unauthorized' ) { return refresh().then((userData) => { if (userData) { // success: set the access token in the current header if (options?.headers) { options.headers = { ...options?.headers, authorization: `Bearer ${userData.accessToken}`, }; } // refetch with the new access token return fetch(uri, options); } else { // failed: move to login screen and logout user history.push('/login'); return fetch(uri, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: ` query { logout } `, variables: {}, }), }); } }); } // no error - repackage and return the current response return new Response(JSON.stringify(bodyJson), options); };