I created a helper function in my React app to fetch the status after fetching a url
:
import { useEffect, useState } from 'react';
const fetchStatusCode = (url: string) => {
const [data, setData] = useState<string | null>(null);
useEffect(() => {
const fetchStatus = async () => {
const response = await fetch(url);
return response.statusText;
};
fetchStatus().then((res) => setData(res));
}, []);
return data;
};
export default fetchStatusCode;
I then use this to conditionally send a custom header in Apollo Client Link operation:
// Apollo Client component file
const isOkStatus = fetchStatusCode('http://my-site.com/abc/token') === 'OK';
const myCustomLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
'my-header': isOkStatus ? 'MyName' : null,
},
};
});
const client: ApolloClient<NormalizedCacheObject> = new ApolloClient({
link: from([errorLink, myCustomLink, httpLink]),
cache: new InMemoryCache(),
typeDefs,
});
Are there ways to refactor this and maybe create a custom React hook instead of a helper function?
Update:
- I changed the function to a hook by renaming it to
useStatusCode
- I use this hook in the Apollo Client file like:
const statusCode = useStatusCode('http://my-site.com/abc/token');
- Maybe one thing to refactor? Use statusCode as a dependency in a useEffect call to conditionally perform the Apollo Client operation. How do I do this in my example above?