Skip to content

Instantly share code, notes, and snippets.

@Caayu
Created March 28, 2022 18:41
Show Gist options
  • Select an option

  • Save Caayu/48016e2b6adfeefacf8fd2a16e2cdaa7 to your computer and use it in GitHub Desktop.

Select an option

Save Caayu/48016e2b6adfeefacf8fd2a16e2cdaa7 to your computer and use it in GitHub Desktop.
pagination.tsx
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() {
// TODO: get data for InfiniteScroll via React Query
const { data, fetchNextPage, hasNextPage, isLoading, isFetching, isError, error } = useInfiniteQuery(
"sw-species",
({ pageParam = initialUrl }) => fetchUrl(pageParam),
{
getNextPageParam: (lastPage) => lastPage.next || undefined
}
)
if (isLoading) return <div className="loading">Loading...</div>;
if (isError) return <div>Error! {error.toString()}</div>;
return (
<>
{ isFetching && <div className="loading">Loading...</div> }
<InfiniteScroll
loadMore={fetchNextPage}
hasMore={hasNextPage}
>
{data.pages.map((pageData) => {
return pageData.results.map(specie => {
return (
<Species
name={specie.name}
language={specie.language}
averageLifespan={specie.average_height}
/>
);
})
})}
</InfiniteScroll>
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment