Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

you make a function type expression like so:

type GetDataArgs = (url: string, options?: any) => Promise<void>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading