Skip to content

Instantly share code, notes, and snippets.

@jimmason
Created July 7, 2023 08:40
Show Gist options
  • Save jimmason/6744c8b31e55b10b4571cd37a7aa790b to your computer and use it in GitHub Desktop.
Save jimmason/6744c8b31e55b10b4571cd37a7aa790b to your computer and use it in GitHub Desktop.
import { ListingCard } from "../components/ListingCard.tsx";
import { useEffect, useState } from "react";
import axios from "axios";
import InfiniteScroll from "react-infinite-scroll-component";
import { Listing } from "../types/Listing.tsx";
import { JsonHeaders } from "../constants/Headers.ts";
import { Loading } from "../components/core/Loading.tsx";
export const Listings = () => {
const [currPage, setCurrPage] = useState(1);
const [listings, setListings] = useState<Listing[]>([]);
const [hasMoreData, setHasMoreData] = useState(true);
const fetchListings = async () => {
const response = await axios({
url: `${import.meta.env.VITE_API_URI}/api/listings?page=${currPage}`,
method: "get",
headers: JsonHeaders,
});
if (response.data.data.length > 0) {
setListings((listings) => listings.concat(response.data.data));
} else {
setHasMoreData(false);
}
};
useEffect(() => {
fetchListings();
}, [currPage]);
const nextPage = () => {
setCurrPage(currPage + 1);
};
return (
<InfiniteScroll
dataLength={listings.length}
next={nextPage}
hasMore={hasMoreData}
loader={<Loading />}
endMessage={
<div className="w-full p-2 text-center">
<p>No more boats match your search</p>
</div>
}
className="flex flex-wrap justify-center"
>
{listings.map((listing, index) => {
return (
<div key={index}>
<ListingCard {...listing} />
</div>
);
})}
</InfiniteScroll>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment