개발자
사진 순서대로 1. 유저 정보 수정 Mutation훅 2. 유저 정보 수정 Mutation훅을 호출하는 컴포넌트 3. 유저 정보를 새로받아오는 Query 훅 입니다. invalidateQueries, refetchQueries, 옵션추가 등등 다해봤는데 쿼리를 무효화하는 요청이 아예안갑니다..ㅜ 쿼리키도 똑같은데 뭐가 문제일까요? 두번째 사진은 흐리게보여서 코드로 올립니다.
1import { useForm } from "react-hook-form"
2import { useNavigate } from "react-router-dom"
3
4import { useUserStore } from "@store/useUserStore"
5import { UPDATE_INPUTS, UPDATE_LIST } from "constants/validation"
6
7import styled from "styled-components"
8
9import Button from "@components/Button/Button"
10import Input from "@components/Input/Input"
11
12import { UpdateUserPayload } from "@typpes/type"
13import { User } from "@typpes/type"
14
15import theme, { fonts } from "@styles/theme"
16
17import { formAdapter } from "@utils/formAdapter"
18
19import { useEditProfile } from "../../../hooks/mutation/useEditProfile"
20
21const UpdateProfile = () => {
22 const navigate = useNavigate()
23
24 const { isLogin, user } = useUserStore()
25 const { register, formState, handleSubmit } = useForm<Omit<User, "sex">>({
26 mode: "onChange",
27 defaultValues: {
28 userName: user?.userName,
29 birthDate: user?.birthDate,
30 loginEmail: user?.loginEmail,
31 },
32 })
33 const { mutate: editUser } = useEditProfile()
34
35 const handleUpdatePaswordPage = () => {
36 navigate("/mypage/password")
37 }
38
39 const handleHome = () => {
40 navigate("/")
41 }
42
43 if (!isLogin) {
44 navigate("/")
45 return null
46 }
47
48 const onSubmit = ({ userName, birthDate }: UpdateUserPayload) => {
49 editUser({ userName, birthDate })
50 }
51
52 return (
53 <UpdateProfileForm
54 noValidate
55 onSubmit={handleSubmit(onSubmit)}>
56 <UpdateProfileTitle>{user?.userName}님의 회원정보</UpdateProfileTitle>
57 <UpdateProfileList>
58 {UPDATE_LIST.PROFILE.map(({ id, name, label, isDisabled }) => (
59 <Input key={id}>
60 <Input.Label htmlFor={name}>{label}</Input.Label>
61 <Input.Input
62 variant="edit"
63 props={{
64 ...formAdapter({
65 register,
66 name,
67 validator: UPDATE_INPUTS.PROFILE[name],
68 $isDirty: !!formState.dirtyFields[name],
69 $isError: !!formState.errors[name],
70 }),
71 disabled: isDisabled,
72 defaultValue: name,
73 }}
74 />
75 <Input.Error>{formState?.errors[name]?.message}</Input.Error>
76 </Input>
77 ))}
78 </UpdateProfileList>
79 <UpdatePasswordButton
80 type="button"
81 onClick={handleUpdatePaswordPage}>
82 비밀번호 변경하기
83 </UpdatePasswordButton>
84 <UpdateButtonContainer>
85 <Button
86 variant="text"
87 size="full"
88 type="button"
89 onClick={handleHome}>
90 취소
91 </Button>
92
93 <Button
94 variant="main"
95 size="full"
96 type="submit">
97 회원정보 변경 완료
98 </Button>
99 </UpdateButtonContainer>
100 </UpdateProfileForm>
101 )
102}
103
104export default UpdateProfile
답변 1
코드를 보기가 너무 어렵군요. 가독성이 좋지 않아보입니다. 개선할 수 있다면 개선 하시구요, (카멜 케이스로 썼다가 대문자로 썼다가 언더바 썼다가.. 변수명이나 타입명의 패턴을 될수 있으면 하나, 혹은 둘 정도로 통일해 주십시오.) invalidateQueries가 안된다면 우선 useMutation의 onSuccess가 정상적으로 실행은 되는지 확인해보시면 좋을 것 같습니다. editUser가 정상적으로 수행된다면, onSuccess의 위치 문제인 것 같습니다. useMutation에 익숙치 않다면 try catch로 API post나 put을 날리고 response를 체크하는 방식으로 수정하신뒤 finally에서 invalidate를 걸어 보시죠. 그렇게 해서 invalidate가 실행된다면 그 소스는 백업해두고 useMutation으로 바꾸고 다시 비교 분석을 진행해보시는게 어떨까 합니다. 그럼 즐거운 개발 되세요.
익명
작성자
2024년 11월 29일
감사합니다!!
익명
작성자
2024년 11월 29일
onSuccess 내부에서 콘솔을 찍어보니까 onSuccess는 발동은 되네요. try, catch문에서 invalidateQueries를 해도 요청이 안가네요. finally문에서 콘솔은 찍히고 response도 잘 옵니다.
지금 가입하면 모든 질문의 답변을 볼 수 있어요!
현직자들의 명쾌한 답변을 얻을 수 있어요.
이미 회원이신가요?
커리어리 AI 봇
GPT가 달아주는 답변입니다.
2024년 11월 28일
이 문제를 해결하려면 먼저 useMutation 훅의 성공적인 요청 후에 invalidateQueries를 호출해야 합니다. 이는 아래와 같은 방법으로 구현할 수 있습니다: ```javascript import { useMutation, useQueryClient } from 'react-query'; const mutation = useMutation(updateUser, { onSuccess: () => { queryClient.invalidateQueries('user'); }, }); ``` 위 예제에서 `updateUser`는 유저 정보 수정 함수이며, 'user'는 새로받아오는 Query의 key입니다. 만일 여러 keys를 사용하는 경우, invalidateQueries 함수에 배열을 넘겨줍니다. ``` javascript queryClient.invalidateQueries(['user', userId]); ``` `userId`가 동적인 값인 경우 이와 같이 사용 가능합니다. 추가로 refetchQueries 옵션을 사용해보셨다면, 해당 옵션은 Apollo Client의 기능으로 React Query에는 존재하지 않으니 착각하지 않도록 주의하시기 바랍니다.
지금 가입하면 모든 질문의 답변을 볼 수 있어요!