Ask Your Question
3

How can I utilize the precise type for the data returned in a React hook based on type arguments in Typescript?

asked 2022-04-21 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-03-24 17:00:00 +0000

lalupa gravatar image

To utilize the precise type for the data returned in a React hook based on type arguments in Typescript, you can define the return type of the hook using a generic type parameter. Here's an example:

interface User {
  id: number;
  name: string;
}

function useFetchData<T>(url: string): { data: T | null; loading: boolean; error: string | null } {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetch(url)
      .then((response) => response.json())
      .then((result) => {
        setData(result as T);
      })
      .catch((e) => {
        setError(e.message);
      })
      .finally(() => {
        setLoading(false);
      });
  }, [url]);

  return { data, loading, error };
}

const UsersList = () => {
  const { data, loading, error } = useFetchData<User[]>('/users');

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;

  return (
    <ul>
      {data?.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
};

In this example, useFetchData is a custom hook that takes a URL and returns an object with data, loading, and error properties. The T generic type parameter specifies the type of data that the hook should return.

In the UsersList component, we pass User[] as the type argument to useFetchData to indicate that we're expecting an array of User objects. The TypeScript compiler will enforce the type of data to be User[] | null.

By using generic type parameters, we can ensure that the data returned by our hook has the correct type, and we can avoid type errors when using the data in our components.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-21 11:00:00 +0000

Seen: 10 times

Last updated: Mar 24 '23