useMutation의 mutate 타입스크립트 에러 해결법: mutateFn에 전달하는 데이터에 타입 명시하기

Sheryl Yun·2023년 1월 6일
0

원티드 챌린지에서 useMutation으로 회원가입을 구현하던 중 다음과 같은 에러가 발생했다.

Argument of type '{ email: string; password: string; }' is not assignable to parameter of type 'void'

구체성을 줄이고자 에러 메시지의 뒷부분('~ is not')부터 검색했는데 stackoverflow에 나의 경우와 거의 비슷한 질문이 있었다.

stackoverflow 링크

mutate의 첫 번째 인자useMutation의 function(mutationFn)에 전달할 데이터이다.

타입스크립트는 전달하는 데이터, 그 데이터를 받는 자리 모두 타입이 지정되어 있어야 한다.

에러가 난 상황은 전달하는 데이터의 타입은 명시되었지만(userValue, { email: string; password: string; }), 데이터를 받는(사용하는) 자리에서는 userData가 어떤 타입인지 모르기 때문에(mutationFn의 userData 인자) 에러가 발생했다.

따라서 mutationFn에 전달될 데이터인 userData에 타입을 명시해주면 해결된다.

const queryClient = useQueryClient();

  const [userValue, setUserValue] = useState({
    email: '',
    password: '',
  });
  const [passwordConfirm, setPasswordConfirm] = useState({
    passwordConfirm: '',
  });

  const registerAPI = () => axios.post('http://localhost:8080/data');

  const { data, isLoading, mutate } = useMutation({
    mutationFn: (userData: UserProp) => // 여기에 UserProp으로 타입을 명시해주었다
      axios.post('http://localhost:8080/data', userData),
  });

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    queryClient.setQueryData([queryKeys.REGISTER_USER], userValue);

    mutate(userValue, { // 에러가 나던 곳
      onSuccess: () => {
        console.log('회원가입 정보 저장 성공!');
        navigate('/');
      },
      onError: (error) => {
        console.log(error);
      },
    });
  };
  
  return (
  ...
profile
데이터 분석가 준비 중입니다 (티스토리에 기록: https://cherylog.tistory.com/)

0개의 댓글