[React Query] Infinite scroll

gyujae·2022년 9월 7일
0
post-custom-banner

useInfiniteQuery 구조

const { data, hasNextPage, fetchNextPage, isLoading, isError,  error, isFetching} = useInfiniteQuery('sw-species', ({ pageParam = initialUrl }) => fetchUrl(initialUrl), {
    getNextPageParam: (lastPage) => lastPage.next || undefined
  })

InfiniteScroll

react native FlatList. react query와 호환성이 좋음.

npm install react-infinite-scroller
<InfiniteScroll hasMore={hasNextPage} loadMore={fetchNextPage}>
  {data.pages.map(pageData => {
    return pageData.results.map(specie => {
      return (
        <Species
          key={specie.name}
          name={specie.name}
          language={specie.language}
          averageLifespan={specie.average_lifespan}
          />
      )
    })
  })}
</InfiniteScroll>

isLoading && isFetching

isFetching을 쓰게 다면 기존에 데이터를 다시 보여줘 isLoading을 써야 한다.

if (isLoading) return <div className="loading">Loading...</div>

전체 코드

import InfiniteScroll from "react-infinite-scroller";
import { useInfiniteQuery } from "react-query";
import { Species } from "./Species";

const initialUrl = "https://swapi.dev/api/species/";
const fetchUrl = async (url) => {
  const response = await fetch(url);
  return response.json();
};

export function InfiniteSpecies() {
  const { data, hasNextPage, fetchNextPage, isLoading, isError,  error, isFetching} = useInfiniteQuery('sw-species', ({ pageParam = initialUrl }) => fetchUrl(initialUrl), {
    getNextPageParam: (lastPage) => lastPage.next || undefined
  })

  if (isLoading) return <div className="loading">Loading...</div>
  if (isError) return <div className="loading">Error: { error.toString()}</div>
  return (
    <>
      {isFetching && <div className="loading">Fetching...</div>}
      <InfiniteScroll hasMore={hasNextPage} loadMore={fetchNextPage}>
        {data.pages.map(pageData => {
            return pageData.results.map(specie => {
              return (
                <Species
              key={specie.name}
              name={specie.name}
              language={specie.language}
              averageLifespan={specie.average_lifespan}
            />
              )
            })
        })}
      </InfiniteScroll>
    </>
  )
}

post-custom-banner

0개의 댓글