Skip to content

Commit

Permalink
Reduce amount of API calls (#564)
Browse files Browse the repository at this point in the history
  • Loading branch information
ivntsng authored Nov 9, 2024
1 parent 48d4146 commit 3351b0e
Showing 1 changed file with 6 additions and 13 deletions.
19 changes: 6 additions & 13 deletions frontend/src/components/pages/Listing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,12 @@ const Listing = () => {
const [isFetched, setIsFetched] = useState(false);

const fetchListing = useCallback(async () => {
if (listing !== null) {
return;
}

if (!username || !slug) {
addErrorAlert(new Error("Invalid URL parameters"));
return;
}

try {
// Try to fetch the listing using the username/slug endpoint
const response = await auth.client.GET("/listings/{username}/{slug}", {
params: {
path: { username, slug },
Expand All @@ -42,23 +37,21 @@ const Listing = () => {
} catch (err) {
addErrorAlert(err);
}
}, [listing, username, slug, auth.client, addErrorAlert]);
}, [username, slug, auth.client, addErrorAlert]);

useEffect(() => {
fetchListing();
}, [fetchListing]);
const shouldFetch =
(listing === null && username && slug) ||
(auth.isAuthenticated && !isFetched);

// Refetch the listing when auth state changes or on initial load
useEffect(() => {
if (auth.isAuthenticated || !isFetched) {
if (shouldFetch) {
fetchListing();
}
}, [auth.isAuthenticated, isFetched, fetchListing]);
}, [username, slug, auth.isAuthenticated, isFetched, listing, fetchListing]);

useEffect(() => {
setListing(null);
setIsFetched(false);
fetchListing();
}, [username, slug]);

return (
Expand Down

0 comments on commit 3351b0e

Please sign in to comment.