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.
Asked: 2022-04-21 11:00:00 +0000
Seen: 10 times
Last updated: Mar 24 '23