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

How to specify response type in useFetch hook

I have a useFetch custom hook implemented as follows:

function useFetchDemo<ResponseType>(url: string): {
  data: ResponseType;
} {
  const [data, setData] = useState<ResponseType | null>(null);

  useEffect(() => {
    axios.get(url).then((res) => setData(res["data"]));
  }, []);

  return { data };
}

I intend to use it like
useFetch<UserInterface>("/users/123") or useFetch<PostInterface>("/posts/123"), which allows me to specify the response data type based on which endpoint I am querying.

However, I am getting the error:

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

Type 'ResponseType | null' is not assignable to type 'ResponseType'.
  'ResponseType' could be instantiated with an arbitrary type which could be unrelated to 'ResponseType | null'.ts(2322)

Seems like I should be passing a different initial value to useState but I don’t know what value I should use.

>Solution :

function useFetchDemo<ResponseType>(url: string): {
  data: ResponseType | null;
} {
  const [data, setData] = useState<ResponseType | null>(null);

  useEffect(() => {
    axios.get<ResponseType>(url).then((res) => setData(res["data"]));
  }, []);

  return { data };
}

pass your response type to the axios get request. There is generic get method defined in axios/index.d.ts

get<T = never, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig<T>): Promise<R>;

this way data will be the type you passed.

Next to that also add the null option to data

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