react-query를 써보자..

준영·2023년 3월 16일
0

이것저것..

목록 보기
8/17

react-query란

React Query는 React 애플리케이션에서 데이터를 가져오고 관리하는 라이브러리이다. 이를 사용하면 API 호출을 간단하게 처리할 수 있고, 캐싱과 자동 업데이트 기능을 통해 데이터를 더 효율적으로 관리할 수 있다.

React Query를 사용하면, 이전에 호출한 결과를 캐싱하여 동일한 요청이 있을 경우에는 API 호출을 다시 하지 않는다. 또한, 자동으로 데이터를 업데이트하여 최신 정보를 보여주며, 이를 통해 코드를 더 간결하게 작성할 수 있다.

따라서, React Query는 데이터를 가져오고 관리하는 작업을 단순화하고, 개발자가 더 적은 코드를 작성하여 빠르게 애플리케이션을 개발할 수 있도록 도와준다.

사용하기

패키지 설치

npm install react-query

_app.tsx

import "../styles/globals.css";
import Layout from "../components/Layout/Layout";
import { appWithTranslation } from "next-i18next";
import { RecoilRoot } from "recoil";
// react-query
import { QueryClient, QueryClientProvider } from "react-query";

const queryClient = new QueryClient();

function MyApp({ Component, pageProps }) {
  return (
    <QueryClientProvider client={queryClient}>
      <RecoilRoot>
        <Layout>
          {/* <LocaleButton /> */}
          <Component {...pageProps} />
        </Layout>
      </RecoilRoot>
    </QueryClientProvider>
  );
}

export default appWithTranslation(MyApp);

QueryClientProvider로 감싸준다.

List.tsx

// import ...

// react-query
import { useMutation, useQuery, useQueryClient } from "react-query";

export default function VisitLog() {
  // fetch comments func
  async function fetchComments() {
    const visitlog = collection(getFirestore(firebaseApp), "visitlog");
    const result = await getDocs(query(visitlog, orderBy("timestamp", "desc")));
    const fetchData = result.docs.map((el) => el.data());
    return fetchData;
  }

  // delete comment func
  const deleteCommentFunc = async (id) => {
    await deleteDoc(doc(firebaseDb, "visitlog", id)).then(() => {
      try {
        console.log("done");
        return;
      } catch (err) {
        console.log(err);
        return;
      }
    });
  };

  // create comment func
  const createCommentFunc = async () => {
    if (loginStatus == true && userInfo.email != "") {
      if (comment != "") {
        const id = uuidv4();
        await setDoc(doc(firebaseDb, "visitlog", id), {
          id: id,
          name: name,
          comment: comment,
          timestamp: new Date(),
        });
        // fetchComments();
        setComment("");
        listRef.current.scrollTop = 0;
      } else {
        alert("Please enter a comment");
      }
    } else {
      router.push("/login");
    }
  };
  
  // 온클릭 이벤트 타입 문제로 따로 클릭 이벤트를 받는 함수로 뺏음 (코맨트 작성)
  const handleSubmit = (e) => {
    e.preventDefault();
    createComment();
  };

  const queryClient = useQueryClient();

  // fetch
  const { isLoading, data: commentsData } = useQuery("visitlog", fetchComments);
  // delete
  const { mutate: deleteComment } = useMutation(deleteCommentFunc, {
    onSuccess: () => {
      queryClient.invalidateQueries("visitlog");
    },
  });
  // create
  const { mutate: createComment } = useMutation(createCommentFunc, {
    onSuccess: () => {
      queryClient.invalidateQueries("visitlog");
    },
  });

  // another state...

  return (
	// ...
  );
}
  1. React Query의 useQuery hook을 사용하여 데이터를 가져온다. useQuery hook은 데이터를 가져오는데 필요한 매개변수와 함께 호출된다.

  2. useQuery hook은 첫 번째 매개변수로 데이터 식별자를 받는다. 이 식별자는 데이터의 고유한 키 값으로 사용된다. 두 번째 매개변수는 데이터를 가져오는 함수이고, 이 함수는 API 호출을 수행하고 데이터 결과를 리턴해준다.

  3. isLoading, error, data와 같은 여러 가지 변수를 사용하여 데이터 상태를 처리합니다. 이 변수들은 useQuery hook에서 반환됩니다.

    • isLoading은 api를 호출하고 완료까지의 과정을 boolean으로 나타내준다. (스켈레톤 디자인 적용하는데 유용했음)
  4. 또한 useMutation hook을 사용하여 데이터를 업데이트(수정, 삭제)하는 함수를 만들 수 있다.

    onSuccess: () => {
      queryClient.invalidateQueries("visitlog");
    },
    // 성공적으로 뮤테이션이 처리된다면, "visitlog"에 대한 캐시가 삭제되고,
    // 이후에 해당 쿼리를 실행할 때 새로운 데이터를 가져오겠다는 뜻

결과

visitlog를 보면 캐싱된 데이터와 비교해서 렌더링이 필요 없음을 보고, api를 호출하지 않는 모습을 볼 수 있다. (스켈레톤 디자인이 보이지 않음)

profile
개인 이력, 포폴 관리 및 기술 블로그 사이트 👉 https://aimzero-web.vercel.app/

0개의 댓글