Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript function with generic type in useState, allow nullable

I have a hook function like this in React:

export function useFetch<T = unknown|null>(url: string) : [T, boolean] {
  const accessToken = useAccessToken();
  const [data, setData] = useState<T>(null);  // TS ERROR
  const [isLoading, setIsLoading] = useState<boolean>(true);
  
  useEffect(() => {
    if (accessToken) {
      fetch(`/api/v1${url}`, {
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      })
        .then((res) => res.json())
        .then(data => {
          setData(data);
          setIsLoading(false);
        });
    }
  }, [accessToken, url]);
  return [data, isLoading];
}

But I get this error: Argument of type 'null' is not assignable to parameter of type 'T | (() => T)'.ts(2345)

How can I define T as nullable?

like image 421
roeland Avatar asked Mar 28 '26 01:03

roeland


1 Answers

T = unknown | null is a default for generic type parameter, it doesn't mean that provided T will allow null. Instead you can specify that null is allowed for state in addition to T:

export function useFetch<T>(url: string): [T | null, boolean] {
    const accessToken = useAccessToken();
    const [data, setData] = useState<T | null>(null);
    const [isLoading, setIsLoading] = useState<boolean>(true);

    // ...
    return [data, isLoading];
}

Playground

like image 63
Aleksey L. Avatar answered Mar 29 '26 21:03

Aleksey L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!