react query infinity 예제

column clash·2021년 12월 30일
0

simple 기본

import {  IProduct } from "@src/typings/db";
import axios from "axios";
import { useInfiniteQuery } from "react-query";

const useInfinity = (querykey: string) => {
  // useInfiniteQuery에서 쓸 함수
  const fetchPosts = async ({ pageParam = 1 }) => {
    const response = await axios.get(
      `/api/product?meetingcycle=${querykey}&limit=12&page=${pageParam}`
    );
    const result: { products: IProduct[]; is_last: boolean } = response.data;
    // axios로 받아온 데이터를 다음과 같이 변경!

    return {
      products: result.products,
      nextPage: pageParam + 1,
      isLast: result.is_last
    };
  };

  const query = useInfiniteQuery(["list", querykey], fetchPosts, {
    getNextPageParam: (lastPage, pages) => {
      if (!lastPage.isLast) return lastPage.nextPage;
      return undefined;
    },
    refetchOnWindowFocus: false,
    refetchOnMount: true,
    refetchOnReconnect: true,
    retry: 1
  });

  return query;
};

export { useInfinity };
profile
풀스택 개발 중...

0개의 댓글