Home > Blockchain >  Typescript: reusing a non-functional component's types; refactoring
Typescript: reusing a non-functional component's types; refactoring

Time:11-21

I'm trying to figure out how to refactor a function's types. From reading the docs, I couldn't seem to find much about adding types to non-functional components in my example below.

Notice that you'll see this code repeated twice url: string, options?: any, which leads me to believe that it could be refactored better.

The getData (alias) function declares the type like this: (url: string, options?: any) => Promise<void>;
And the getAllData function declares the type like this: (url: string, options?: any): Promise<void>

Does anyone know how to better refactor these types? The full code of my custom react hook is below for more context:

interface GetDataArgs {
  url: string;
  options?: any;
}

export const useFetch = (): {
  data: any;
  getData: (url: string, options?: any) => Promise<void>;
  fetchError: boolean;
  setData: Dispatch<any>;
} => {
  const [data, setData] = useState<any>(null);
  const [fetchError, setFetchError] = useState<boolean>(false);

  const getAllData = async (url: string, options?: any): Promise<void> => {
    try {
      // loading?
      const res = await fetch(url, options);
      const data = await res.json();
      setData(data);
    } catch (e) {
      setFetchError(true);
      console.error(e);
    }
  };

  return { data, getData: getAllData, fetchError, setData };
};

If you see any other improvements then please feel free to suggest anything. Thank you

CodePudding user response:

you make a function type expression like so:

type GetDataArgs = (url: string, options?: any) => Promise<void>
  • Related