Files
scriptshare-cursor-clone/src/hooks/useUsers.ts

96 lines
3.0 KiB
TypeScript

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import * as usersApi from '@/lib/api/users';
import { showSuccess, showError } from '@/utils/toast';
// Query keys
export const userKeys = {
all: ['users'] as const,
lists: () => [...userKeys.all, 'list'] as const,
details: () => [...userKeys.all, 'detail'] as const,
detail: (id: string) => [...userKeys.details(), id] as const,
search: (query: string) => [...userKeys.all, 'search', query] as const,
};
// Get user by ID
export function useUser(id: string) {
return useQuery({
queryKey: userKeys.detail(id),
queryFn: () => usersApi.getUserById(id),
enabled: !!id,
staleTime: 5 * 60 * 1000,
});
}
// Get all users (admin only)
export function useUsers(limit?: number, offset?: number) {
return useQuery({
queryKey: [...userKeys.lists(), limit, offset],
queryFn: () => usersApi.getAllUsers(limit, offset),
staleTime: 5 * 60 * 1000,
});
}
// Search users
export function useSearchUsers(query: string, limit?: number) {
return useQuery({
queryKey: userKeys.search(query),
queryFn: () => usersApi.searchUsers(query, limit),
enabled: !!query && query.length >= 2,
staleTime: 2 * 60 * 1000, // 2 minutes for search results
});
}
// Create user mutation
export function useCreateUser() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: usersApi.createUser,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: userKeys.lists() });
showSuccess('User created successfully!');
},
onError: (error: any) => {
showError(error.message || 'Failed to create user');
},
});
}
// Update user mutation
export function useUpdateUser() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, data }: { id: string; data: usersApi.UpdateUserData }) =>
usersApi.updateUser(id, data),
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: userKeys.detail(data.id) });
queryClient.invalidateQueries({ queryKey: userKeys.lists() });
showSuccess('User updated successfully!');
},
onError: (error: any) => {
showError(error.message || 'Failed to update user');
},
});
}
// Update user permissions mutation (admin only)
export function useUpdateUserPermissions() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, permissions }: {
id: string;
permissions: { isAdmin?: boolean; isModerator?: boolean }
}) => usersApi.updateUserPermissions(id, permissions),
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: userKeys.detail(data.id) });
queryClient.invalidateQueries({ queryKey: userKeys.lists() });
showSuccess('User permissions updated successfully!');
},
onError: (error: any) => {
showError(error.message || 'Failed to update user permissions');
},
});
}