[유데미] React Query : React로 서버 상태 관리하기
📍Mutation
- 서버에 있는 데이터를 수정하는 네트워크 통신을 만드는 것
(e.g. 블로그 제목을 바꾸거나 등)
📍useMutation
몇가지를 제외하면 useQuery와 비슷
- mutate 함수를 반환
- 데이터를 받아오지 않으므로 query key가 없어도 됨
- isLoading만 있고 isFetching은 없음
- isError의 재시도 횟수가 디폴트 0 (useQuery는 3회)
📍jsonplaceholder API는 실제로 데이터를 삭제하거나 수정하지 않음을 주의
- 단지 삭제나 수정 결과를 반환해줌
- Delete 요청이 성공적으로 전송됐는지는 유저에게 알려줄 수 있음
📍단계
1️⃣import useMutation
2️⃣useMutation 훅을 deleteMutation 변수에 할당
- useMutation 훅도 useQuery 훅과 비슷함
- 단, 이미 useQuery에서 구조분해할당으로 data 등을 사용중이라면, 혼동을 방지하기 위해, 구조분해할당을 피하는 것이 좋음
const deleteMutation = useMutation({
mutationFn: (postId: number) => deletePost(postId),
});
3️⃣delete 버튼에 click 이벤트핸들러로 deleteMutation.mutate(post.id) 를 부착
- post.id는 삭제할 포스트의 id
- 인수가 있으므로 콜백 함수 형태로 전
4️⃣jsonplaceholder 특성 상 isSuccess 상태를 통해 삭제됐는지 확인
// delete button
<button onClick={() => deleteMutation.mutate(post.id)}>Delete</button>
// HTTP 요청의 상태
{deleteMutation.isError && (
<p style={{ color: "red" }}>Error deleting the post</p>
)}
{deleteMutation.isLoading && (
<p style={{ color: "purple" }}>Deleting the post</p>
)}
{deleteMutation.isSuccess && (
<p style={{ color: "green" }}>Post has (not) been deleted</p>
)}
📍게시글 제목 수정하기 (Patch)
- PATCH : 일부분만 수정 (body에 바꿀 데이터 일부만 전달)
- PUT : 전체를 교체 (body에 바꿀 데이터를 통으로 전달)
- fetch 함수
async function updatePost(postId: number) {
const response = await fetch(
`https://jsonplaceholder.typicode.com/postId/${postId}`,
{
method: "PATCH",
body: JSON.stringify({
title: "REACT QUERY FOREVER!!!!", // 임의로 입력
}),
}
);
return response.json();
}
- 이외는 deleteMutation과 동일