개인공부/React

react-query: 자동으로 댓글 업데이트 시키기(useMutate, useQuery)

somm12 2023. 6. 27. 14:36

사용하게 된 계기 🧐

개인 프로젝트를 하다가, 댓글을 입력한 뒤에 새로고침없이! 자동으로 업데이트 된 댓글 목록을 불러오게 하고 싶었다.

그래서 react query를 이용해서 useQuery, useMutate를 이용해서 데이터 가져오기, 수정 및 삭제 API 요청 용도로 사용해보기로 했다.!

1. react-query 설치

npm i @tanstack/react-query

2. 앱 최상단에 provider로 감싸주기

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
const queryClient = new QueryClient();// => queryClient 선언해주기
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <BrowserRouter>
    <Provider store={store}>
      <QueryClientProvider client={queryClient}> // => 이부분!
        <App />
      </QueryClientProvider>
    </Provider>
  </BrowserRouter>
);

 

3. API 요청 파일. commentAPI.js

import { useQuery, useQueryClient, useMutation } from "@tanstack/react-query";
import axios from "axios";
// 댓글 가져오기
// query key값이 요청해온 데이터를 매칭
// 데이터가 update가 되면(데이터가 변한다면: 생성 및 삭제 및 수정), 쿼리 키 값을 사용해서 무효화시킴으로써, 
// 데이터를 최신화한다. 자동 댓글 목록 업데이트!
export const useGetComments = (postId) => {
  const data = useQuery(["comment", postId], () => 
    axios.get(`/api/comment/list/${postId}`)
  );

  return data;
};

export const useSubmitComment = (postId, uid, comment) => {
  const queryClient = useQueryClient();

  let body = {
    postId,
    uid,
    comment,
  };
  return useMutation(() => axios.post("/api/comment/submit", body), {
    onSuccess: () => {
      queryClient.invalidateQueries(["comment", postId]);// 무효화 시킴으로써, update.
    },
  });
};

4. front part : upload.jsx ( 댓글 생성)

import { useSubmitComment } from "./commentAPI";
////.....
const { mutate, isSuccess } = useSubmitComment(postId, user.uid, comment);

////..
const submitHandler = (e) => {
    e.preventDefault();
    mutate();
}

 

useMutate가 반환하는 함수, 변수 등 isLoading, isFetching 기능이 많음!! 아래 공식 문서를 잘 읽어봅시다!

 

Mutations | TanStack Query Docs

Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, TanStack Query exports a useMutation hook. Here's an example of a mutation that adds a new todo to the server:

tanstack.com