Home > Mobile >  How to specify response type in useFetch hook
How to specify response type in useFetch hook

Time:07-22

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:

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.

CodePudding user response:

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

  • Related