react-query를 공부하는 도중 아래와 같은 오류 문구를 발견했다.
번역을 해보니 아래와 같았다.
React Hook "useMutation"은 조건부로 호출됩니다. React Hooks는 모든 구성 요소 렌더링에서 정확히 동일한 순서로 호출되어야 합니다. 조기 복귀 후 실수로 React Hook을 호출했습니까?
오류가 발생한 이유는 리액트 Hooks보다 위에서 조기 복귀 즉, return이 있으면 발생하는 오류였다.
Before
{...}
const { data, isLoading, isFetching, refetch, isError, error } = useSuperHeroesData(
onSuccess,
onError
);
if (isLoading || isFetching) {
return <h2>Loading...</h2>;
}
if (isError) {
return <h2>{error.message}</h2>;
}
❗️ 문제가 된 부분 ❗️
const { mutate: addHero } = useMutation(addSuperHero);
const addSuperHero = (hero) => {
return axios.post('http://localhost:4000/superheroes', hero);
};
{...}
After
{...}
const { data, isLoading, isFetching, refetch, isError, error } = useSuperHeroesData(
onSuccess,
onError
);
const { mutate: addHero } = useMutation(addSuperHero);
const addSuperHero = (hero) => {
return axios.post('http://localhost:4000/superheroes', hero);
};
if (isLoading || isFetching) {
return <h2>Loading...</h2>;
}
if (isError) {
return <h2>{error.message}</h2>;
}
{...}
틀린 부분이 있거나 보충해야 할 내용이 있다면 댓글이나 DM(sungstonemin)으로 알려주시면 감사하겠습니다😄