T
TanStack2y ago
extended-salmon

Custom hooks structure

I'm trying to figure out what is a good structure to use for my api, previously a had all those mutation/query hooks in their own usePaginateApi for all my resources which resulted in a mess what usePaginateApi to import. Now I'm trying something new and was thinking about this example below, what are you thoughts? Any better idea's :-)?
export const App: FunctionComponent = () => {
const { useFind } = useUsersApi();
const findApi = useFind({ id: 1337 });

return <Fragment>Status: {findApi.status}</Fragment>;
};
export const App: FunctionComponent = () => {
const { useFind } = useUsersApi();
const findApi = useFind({ id: 1337 });

return <Fragment>Status: {findApi.status}</Fragment>;
};
export const useUsersApi = () => {
const { request } = useApi();
const { sessionToken } = useAuth();

return {
useFind: (params: UserFindParams) =>
useQuery<UserFindData, ApiRequestError>({
queryKey: ['users', 'find', { params }],
queryFn: () => {
return request<UserFindData>(`/internal/v1/users/${params.id}`, {
method: 'GET',
sessionToken,
});
},
}),

useCreate: () =>
useMutation<UserCreateData, ApiRequestError, UserCreateParams>({
mutationFn: (params) =>
request<UserCreateData>(`/internal/v1/users`, {
method: 'POST',
sessionToken,
body: JSON.stringify({
firstName: params.firstName,
lastName: params.lastName,
email: params.email
}),
}),
}),
};
};
export const useUsersApi = () => {
const { request } = useApi();
const { sessionToken } = useAuth();

return {
useFind: (params: UserFindParams) =>
useQuery<UserFindData, ApiRequestError>({
queryKey: ['users', 'find', { params }],
queryFn: () => {
return request<UserFindData>(`/internal/v1/users/${params.id}`, {
method: 'GET',
sessionToken,
});
},
}),

useCreate: () =>
useMutation<UserCreateData, ApiRequestError, UserCreateParams>({
mutationFn: (params) =>
request<UserCreateData>(`/internal/v1/users`, {
method: 'POST',
sessionToken,
body: JSON.stringify({
firstName: params.firstName,
lastName: params.lastName,
email: params.email
}),
}),
}),
};
};
2 Replies
eastern-cyan
eastern-cyan2y ago
how I use is put the queryFn or mutationFn in a different folder api/
extended-salmon
extended-salmonOP2y ago
That is what I did as well but it is kinda hard with the language server to import the correct one as all of these functions have the same name.
No description

Did you find this page helpful?