TanStackT
TanStack2y ago
2 replies
thick-teal

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 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
            }),
          }),
      }),
  };
};
Was this page helpful?