Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/add react query #9

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
},
"dependencies": {
"@heroicons/react": "^2.0.18",
"@tanstack/react-query": "^5.0.5",
"date-fns": "^2.30.0",
"md5": "^2.3.0",
"moviedb-promise": "^4.0.3",
Expand Down
15 changes: 10 additions & 5 deletions src/components/Providers.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
import { HelmetProvider } from "react-helmet-async";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

import { UserProvider } from "../hooks/useUser";
import { ListProvider } from "../hooks/useList";
import { ListModalProvider } from "../hooks/useListModal";

const queryClient = new QueryClient();

const Providers = ({ children }: { children: React.ReactNode }) => {
return (
<HelmetProvider>
<UserProvider>
<ListProvider>
<ListModalProvider>{children}</ListModalProvider>
</ListProvider>
</UserProvider>
<QueryClientProvider client={queryClient}>
<UserProvider>
<ListProvider>
<ListModalProvider>{children}</ListModalProvider>
</ListProvider>
</UserProvider>
</QueryClientProvider>
</HelmetProvider>
);
};
Expand Down
242 changes: 61 additions & 181 deletions src/components/pages/Home.tsx
Original file line number Diff line number Diff line change
@@ -1,161 +1,48 @@
import { useEffect, useRef, useState } from "react";
import { useEffect, useMemo, useRef } from "react";
import { Helmet } from "react-helmet-async";
import { useSearchParams } from "react-router-dom";
import type { SearchMultiResponse } from "moviedb-promise/dist/request-types";

import Pagination from "../search/Pagination";
import TabButton from "../search/TabButton";
import ListItem from "../lists/ListItem";

import {
formatSearchAll,
formatSearchMovie,
formatSearchPerson,
formatSearchTvShow,
ListItem as ListItemType,
} from "../../lib/format";
import type { ApiError, ApiResponse } from "../../lib/api";
import { searchMovie } from "../../lib/api/movie";
import { searchPerson } from "../../lib/api/person";
import { searchAll, getTrending } from "../../lib/api/search";
import { searchTv } from "../../lib/api/tvShow";
import { useGetListing } from "../../hooks/useGetListing";

type Tab = "all" | "movie" | "tv" | "person";

const Home = () => {
const [searchParams, setSearchParams] = useSearchParams();

const [searchResults, setSearchResults] = useState<
ApiResponse<SearchMultiResponse> | undefined
>(undefined);
const [formattedResults, setFormattedResults] = useState<ListItemType[]>([]);

const tabRef = useRef<HTMLDivElement>(null);

const search = searchParams.get("search") || "";
const tab = (searchParams.get("tab") || "all") as Tab;
const page = parseInt(searchParams.get("page") || "1");

useEffect(() => {
let isCancelled = false;

setSearchResults({ status: "pending" });

if (search && search.trim() !== "") {
if (tabRef.current) {
tabRef.current.scrollIntoView({ behavior: "smooth" });
}
const { page, search, tab } = useMemo(() => {
const search = searchParams.get("search") || "";
const tab = (searchParams.get("tab") || "all") as Tab;
const page = parseInt(searchParams.get("page") || "1");

switch (tab) {
case "all":
searchAll({
query: search,
page,
})
.then((data) => {
if (!isCancelled) {
setSearchResults({ status: "resolved", data });
setFormattedResults(formatSearchAll(data));
}
})
.catch((error: ApiError) => {
if (!isCancelled) {
// TODO: Handle error
setSearchResults({ status: "rejected", error });
setFormattedResults([]);
}
});

break;
case "movie":
searchMovie({
query: search,
page,
})
.then((data) => {
if (!isCancelled) {
setSearchResults({ status: "resolved", data });
setFormattedResults(formatSearchMovie(data));
}
})
.catch((error: ApiError) => {
if (!isCancelled) {
// TODO: Handle error
setSearchResults({ status: "rejected", error });
setFormattedResults([]);
}
});

break;
case "tv":
searchTv({
query: search,
page,
})
.then((data) => {
if (!isCancelled) {
setSearchResults({ status: "resolved", data });
setFormattedResults(formatSearchTvShow(data));
}
})
.catch((error: ApiError) => {
if (!isCancelled) {
// TODO: Handle error
setSearchResults({ status: "rejected", error });
setFormattedResults([]);
}
});
return {
search,
tab,
page,
};
}, [searchParams]);

break;
case "person":
searchPerson({
query: search,
page,
})
.then((data) => {
if (!isCancelled) {
setSearchResults({ status: "resolved", data });
setFormattedResults(formatSearchPerson(data));
}
})
.catch((error: ApiError) => {
if (!isCancelled) {
// TODO: Handle error
setSearchResults({ status: "rejected", error });
setFormattedResults([]);
}
});
const hasSearchTerm = search.trim() !== "";

break;
default:
// Something went wrong!
setSearchResults({ status: "rejected" });
setFormattedResults([]);
const { isLoading, results } = useGetListing({
type: hasSearchTerm ? tab : "trending",
args: {
page,
query: search,
},
});

break;
}
} else {
// Default to trending today
getTrending()
.then((data) => {
if (!isCancelled) {
setSearchResults({ status: "resolved", data });
setFormattedResults(formatSearchAll(data));
}
})
.catch((error: ApiError) => {
if (!isCancelled) {
// TODO: Handle error
setSearchResults({ status: "rejected", error });
setFormattedResults([]);
}
});
useEffect(() => {
// Scroll back to the top on page or query change
if (hasSearchTerm && tabRef.current) {
tabRef.current.scrollIntoView({ behavior: "smooth" });
}

return () => {
isCancelled = true;
};
}, [search, page, tab]);
}, [hasSearchTerm, page, tab]);

const handleSearch = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
Expand Down Expand Up @@ -236,9 +123,9 @@ const Home = () => {
</div>
</form>

{searchResults ? (
{results ? (
<div className="mt-16" ref={tabRef}>
{!search ? (
{!hasSearchTerm ? (
<div className="border-b border-gray-200 pb-5">
<h3 className="text-lg font-medium leading-6 text-gray-900">
Trending today
Expand Down Expand Up @@ -303,47 +190,40 @@ const Home = () => {
</>
)}

{searchResults.status !== "rejected" ? (
<>
<ul className="mt-8 grid grid-cols-2 gap-x-4 gap-y-8 sm:grid-cols-4 sm:gap-x-6 lg:grid-cols-5 lg:gap-x-8 xl:gap-x-12">
{searchResults.status === "pending" ? (
<>
{Array(20)
.fill(null)
.map((_, index) => (
<li key={index} className="animate-pulse">
<div className="group aspect-w-2 aspect-h-3 block w-full overflow-hidden rounded-lg bg-gray-100" />
<div className="mt-2 h-4 w-3/4 rounded bg-gray-100" />
<div className="mt-1 h-4 w-1/2 rounded bg-gray-100" />
</li>
))}
</>
) : (
<>
{formattedResults.map((result) => (
<li key={result.tmdbId} className="relative">
<ListItem item={result} action="add" />
</li>
))}
</>
)}
</ul>

{search &&
searchResults.status === "resolved" &&
searchResults.data.total_pages &&
searchResults.data.total_pages > 1 ? (
<Pagination
currentPage={page}
totalPages={searchResults.data.total_pages}
onChange={(newPage) => {
searchParams.set("page", newPage.toString());

setSearchParams(searchParams);
}}
/>
) : null}
</>
<ul className="mt-8 grid grid-cols-2 gap-x-4 gap-y-8 sm:grid-cols-4 sm:gap-x-6 lg:grid-cols-5 lg:gap-x-8 xl:gap-x-12">
{isLoading ? (
<>
{Array(20)
.fill(null)
.map((_, index) => (
<li key={index} className="animate-pulse">
<div className="group aspect-w-2 aspect-h-3 block w-full overflow-hidden rounded-lg bg-gray-100" />
<div className="mt-2 h-4 w-3/4 rounded bg-gray-100" />
<div className="mt-1 h-4 w-1/2 rounded bg-gray-100" />
</li>
))}
</>
) : (
<>
{results.items.map((item) => (
<li key={item.tmdbId} className="relative">
<ListItem item={item} action="add" />
</li>
))}
</>
)}
</ul>

{results.total > 1 ? (
<Pagination
currentPage={page}
totalPages={results.total}
onChange={(newPage) => {
searchParams.set("page", newPage.toString());

setSearchParams(searchParams);
}}
/>
) : null}
</div>
) : null}
Expand Down
2 changes: 2 additions & 0 deletions src/hooks/useGetListing/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./useGetListing";
export * from "./types";
13 changes: 13 additions & 0 deletions src/hooks/useGetListing/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { ListItem } from "../../lib/format";

export type SearchType = "all" | "movie" | "tv" | "person";

export type SearchArgs = {
query: string;
page: number;
};

export type ListingResponse = {
items: ListItem[];
total: number;
};
Loading