Hey there, I'm looking to create reusable hooks for API requests. Here's the code I have so far:
interface DataResponse<Data> {
data: Data[];
}
export const useRequestInfiniteHooks = <T extends DataResponse<T>>() => {
const url = "/lms/class/all";
const result = apiRequest()
const mappedData: T['data'] = mappingData()
return {data: mappedData};
};
type ClassesResponse = {
data: {
id: string;
title: string;
}[];
total: number;
};
const MantapComponent = () => {
const { data } = useRequestInfiniteHooks<ClassesResponse>();
};
I want the data to contain the type that's passed to the generic call. It seems to be getting the type, but the hook call isn't satisfied.
Here's the error response I'm getting:
https://i.sstatic.net/uEwT4.png
Type 'ClassesResponse' does not satisfy the constraint 'DataResponse<ClassesResponse>'.
Types of property 'data' are incompatible.
Type '{ id: string; title: string; }[]' is not assignable to type 'ClassesResponse[]'.
Type '{ id: string; title: string; }' is missing the following properties from type 'ClassesResponse': data, totalts(2344)
type ClassesResponse = {
data: {
id: string;
title: string;
}[];
total: number;
}
What should I do to satisfy this hook call?
I've tried calling it like this, but I still get the error:
https://i.sstatic.net/q6pDz.png
Type 'DataResponse<ClassesResponse>' does not satisfy the constraint 'DataResponse<DataResponse<ClassesResponse>>'.
Type 'ClassesResponse' is not assignable to type 'DataResponse<ClassesResponse>'.
Types of property 'data' are incompatible.
Type 'Class[]' is not assignable to type 'ClassesResponse[]'.
Type 'Class' is missing the following properties from type 'ClassesResponse': data, totalts(2344)
type ClassesResponse = {
data: Class[];
total: number;
}
I have read the documentation here, but it only shows how to create the function with generics, not how to call it properly to match the type passed.
So, my question is, how can I satisfy that hook/function call?