Skip to content

Instantly share code, notes, and snippets.

@abel-masila
Created April 25, 2024 22:38
Show Gist options
  • Save abel-masila/d33326702034d1de7619d689a4fcc068 to your computer and use it in GitHub Desktop.
Save abel-masila/d33326702034d1de7619d689a4fcc068 to your computer and use it in GitHub Desktop.
// Custom hook for mutations
const useCustomMutation = <T = unknown>(
mutationFn: (...args: any[]) => Promise<T>,
options?: UseMutationOptions<T, unknown, unknown>
) => {
return useMutation(mutationFn, {
onSuccess: (data) => {
// Handle success case
console.log('Mutation successful:', data);
},
onError: (error) => {
// Handle error case
console.error('Mutation failed:', error);
},
...options,
});
};
const useMutateTodo = (options?: UseMutationOptions<Todo, unknown, Todo>) => {
return useCustomMutation(
(data: Todo) => apiClient.post('/todos', data),
options
);
};
// Custom hook for queries
const useCustomQuery = <T = unknown>(
queryFn: (...args: any[]) => Promise<T>,
options?: UseQueryOptions<T, unknown>
) => {
return useQuery(queryFn, {
onSuccess: (data) => {
// Handle success case
console.log('Query successful:', data);
},
onError: (error) => {
// Handle error case
console.error('Query failed:', error);
},
...options,
});
};
const useGetTodos = (options?: UseQueryOptions<Todo[], unknown>) => {
return useCustomQuery(() => apiClient.get<Todo[]>('/todos'), options);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment