Skip to content

Commit a72763a

Browse files
committed
♻️(frontend) Separate mutations from queries for auth logic
Introduces dedicated mutations (for authentication/user operations) separating them from queries to align with best practices for data fetching and state management. Queries remain responsible for READ operations, while mutations now handle CREATE, UPDATE, and DELETE actions (for user data) improving separation of concerns. Signed-off-by: Robin Weber <[email protected]>
1 parent 140d538 commit a72763a

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import {
2+
UseMutationResult,
3+
useMutation,
4+
useQueryClient,
5+
} from '@tanstack/react-query';
6+
7+
import { APIError, errorCauses, fetchAPI } from '@/api';
8+
import { User } from '@/features/auth/api/types';
9+
import { KEY_AUTH } from '@/features/auth/api/useAuthQuery';
10+
11+
type UserUpdateRequest = { id: User['id'] } & Partial<Omit<User, 'id'>>;
12+
13+
async function updateUser(userUpdateData: UserUpdateRequest): Promise<User> {
14+
const response = await fetchAPI(`users/${userUpdateData.id}/`, {
15+
method: 'PATCH',
16+
headers: {
17+
'Content-Type': 'application/json',
18+
},
19+
body: JSON.stringify(userUpdateData),
20+
});
21+
if (!response.ok) {
22+
throw new APIError(
23+
`Failed to update the user`,
24+
await errorCauses(response, userUpdateData),
25+
);
26+
}
27+
return response.json() as Promise<User>;
28+
}
29+
30+
export const useUserUpdate = (): UseMutationResult<
31+
User,
32+
APIError,
33+
UserUpdateRequest
34+
> => {
35+
const queryClient = useQueryClient();
36+
37+
const mutationResult = useMutation<User, APIError, UserUpdateRequest>({
38+
mutationFn: updateUser,
39+
onSuccess: () => {
40+
void queryClient.invalidateQueries({ queryKey: [KEY_AUTH] });
41+
},
42+
onError: (error) => {
43+
console.error('Error updating user', error);
44+
},
45+
});
46+
47+
return mutationResult;
48+
};

0 commit comments

Comments
 (0)