Search code examples
reactjstypescriptreact-hookstypescript-genericsreact-typescript

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?


Solution

  • 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