|
1 | 1 | 'use client'; |
2 | 2 | import { getApi } from '@/app/api/config/appConfig'; |
3 | | -import { useEffect, useState } from 'react'; |
4 | | - |
5 | | -interface Profile { |
6 | | - abvDegree: number; |
7 | | - abvLabel: string; |
8 | | - abvLevel: number; |
9 | | - email?: string; |
10 | | - id: number; |
11 | | - myCommentCount: number; |
12 | | - myKeepCount: number; |
13 | | - myLikedPostCount: number; |
14 | | - myPostCount: number; |
15 | | - nickname: string; |
16 | | -} |
| 3 | +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; |
| 4 | +import { Profile } from '../types/type'; |
17 | 5 |
|
18 | 6 | function useFetchProfile() { |
19 | | - const [profile, setProfile] = useState<Profile | null>(null); |
| 7 | + const queryClient = useQueryClient(); |
20 | 8 |
|
21 | 9 | const fetchProfile = async () => { |
22 | 10 | const res = await fetch(`${getApi}/me/profile`, { |
23 | 11 | method: 'GET', |
24 | 12 | credentials: 'include', |
25 | 13 | }); |
26 | 14 | const json = await res.json(); |
27 | | - setProfile(json.data); |
| 15 | + |
| 16 | + return json.data; |
28 | 17 | }; |
29 | 18 |
|
30 | | - useEffect(() => { |
31 | | - fetchProfile(); |
32 | | - }, []); |
| 19 | + const patchNickName = useMutation({ |
| 20 | + mutationFn: async (nickname: string) => { |
| 21 | + const res = await fetch(`${getApi}/me/profile`, { |
| 22 | + method: 'PATCH', |
| 23 | + credentials: 'include', |
| 24 | + headers: { 'Content-Type': 'application/json' }, |
| 25 | + body: JSON.stringify({ nickname }), |
| 26 | + }); |
| 27 | + if (!res.ok) throw new Error('닉네임 수정 실패'); |
| 28 | + const json = await res.json(); |
| 29 | + return json.data; |
| 30 | + }, |
| 31 | + |
| 32 | + onMutate: async (nickname) => { |
| 33 | + // 같은 키로 요청중인 fetch 중단 |
| 34 | + await queryClient.cancelQueries({ queryKey: ['myProfile'] }); |
| 35 | + // 캐시에 저장된 데이터를 즉시 가져오는 역할 실패시 prev로 롤백 |
| 36 | + const prev = queryClient.getQueryData(['myProfile']); |
| 37 | + // 캐시 내용을 수정 |
| 38 | + queryClient.setQueryData(['myProfile'], (old: Profile) => ({ ...old, nickname })); |
| 39 | + return { prev }; |
| 40 | + }, |
| 41 | + }); |
| 42 | + const profile = useQuery({ queryKey: ['myProfile'], queryFn: fetchProfile }); |
33 | 43 |
|
34 | | - return { profile, fetchProfile }; |
| 44 | + return { fetchProfile, profile, patchNickName }; |
35 | 45 | } |
36 | 46 | export default useFetchProfile; |
0 commit comments