22.12.30 무한스크롤(react-query)

Gon·2022년 12월 30일
0

React Native

목록 보기
2/4
post-thumbnail

무한스크롤

사용자가 페이지 하단에 도달했을 때, 콘텐츠가 계속 로드되는 방식

장점

  1. 클릭하는 것보다 더 나은 사용자 경험
  2. 모바일에 적합
  3. 콘텐츠 탐색 용이

단점

  1. 페이지가 느려짐
  2. 특정 항목 검색이 어려움
  3. 푸터에 접근이 어려움
  4. 사용자가 언제 데이터가 끝나는지 모름

코드

import { View, Text, FlatList, ActivityIndicator } from "react-native";
import { useInfiniteQuery } from "react-query";
import { getData } from "./api";
import List from "./List";

const App = () => {
  const { 
    isLoading, 
    isError, 
    data, 
    error, 
    fetchNextPage, 
    hasNextPage 
  } = useInfiniteQuery("lists", getData, {
    getNextPageParam: (currentPage) => {
      // 데이터마다 다름
      const nextPage = currentPage.page + 1;
      return nextPage > currentPage.total_pages ? null : nextPage;
    },
  });

  if (isLoading) {
    return (
      <>
        <ActivityIndicator />
      </>
    );
  }
  if (isError) return <Text>에러: {error.message}</Text>;

  const loadMore = () => {
    if (hasNextPage) fetchNextPage();
  };

  return (
    <>
      <View style={{ margin: 20 }}>
        <Text style={{ fontSize: 30, color: isDark ? "white" : "black" }}>Lists</Text>
      </View>
      <FlatList
        onEndReached={loadMore}
        onEndReachedThreshold={0.6}
        data={data}
        renderItem={({ item }) => <List item={item} />}
        keyExtractor={(item) => item.id}
        ItemSeparatorComponent={<View style={{ height: 10 }} />}
      />
    </>
  );
};

export default App;

0개의 댓글