0

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:

  1. I changed the function to a hook by renaming it to useStatusCode
  2. I use this hook in the Apollo Client file like: const statusCode = useStatusCode('http://my-site.com/abc/token');
  3. 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?
meez
  • 3,783
  • 5
  • 37
  • 91
  • 1
    Other than the fact that it's not using the naming convention of starting with `use`, it already *is* a custom hook. A custom hook is a function that calls other hooks, and fetchStatusCode does that. I recommend changing the name, but is there anything else you want to change? – Nicholas Tower Nov 02 '22 at 16:37
  • @NicholasTower thanks! I changed it and added an update to my question. Do you know how about point 3? – meez Nov 02 '22 at 18:18

0 Answers0