refactor: clean code and remove unnecessary dependencies

This commit is contained in:
ner committed 2024-09-30 18:54:13 +03:00
1 parent eceae6fec7
commit ebf599eed6
92 files changed
+1152 -2842

No files matched your search

-102
View File
@@ -1,102 +0,0 @@
'use client';
import { forwardRef, useEffect, useLayoutEffect, useRef } from 'react';
import { Virtuoso, VirtuosoHandle, VirtuosoProps } from 'react-virtuoso';
import Card from '@/components/Movie/Card';
const Carousel = ({
index,
movies,
onIndexChange,
onEndReached
}: {
index: number;
movies?: Movie[];
onIndexChange: (index: number) => void;
onEndReached: () => void;
}) => {
const ref = useRef<VirtuosoHandle>(null);
const initialIndex = useRef(index);
useEffect(() => {
const scrollTo = ({ key }: globalThis.KeyboardEvent) => {
if (key === 'ArrowLeft') {
if (index <= 0) return;
ref.current?.scrollIntoView({ index: index - 1, behavior: 'smooth' });
}
if (key === 'ArrowRight') {
if (index >= (movies?.length || 0) - 1) return;
ref.current?.scrollIntoView({ index: index + 1, behavior: 'smooth' });
}
};
document.addEventListener('keydown', scrollTo);
return () => {
document.removeEventListener('keydown', scrollTo);
};
}, [index, movies?.length]);
return (
<div className='card-aspect-ratio mx-auto'>
<Virtuoso
ref={ref}
data={movies}
context={onIndexChange}
endReached={onEndReached}
initialTopMostItemIndex={initialIndex.current}
components={components}
horizontalDirection
skipAnimationFrameInResizeObserver
increaseViewportBy={1000}
/>
</div>
);
};
const components: VirtuosoProps<Movie, (index: number) => void>['components'] = {
Item: ({ item, children, context: onIndexChange, ...props }) => {
const ref = useRef<HTMLDivElement>(null);
const index = props['data-index'];
useLayoutEffect(() => {
const container = ref.current;
if (!container) return;
const observer = new IntersectionObserver(
(entries) =>
entries.forEach((entry) => {
if (!entry.isIntersecting) return;
onIndexChange?.(index);
}),
{
threshold: 0.7
}
);
observer.observe(container);
return () => observer.disconnect();
}, [onIndexChange, index]);
return (
<div {...props} ref={ref} className='snap-start'>
<Card movie={item} />
</div>
);
},
List: forwardRef(function List({ context, ...props }, ref) {
return <div {...props} ref={ref} style={{ ...props.style, display: 'flex' }} className='gap-2' />;
}),
Scroller: forwardRef(function Scroller({ context, ...props }, ref) {
return (
<div {...props} ref={ref} className='overflow-hidden no-scrollbar snap-mandatory snap-x rounded-lg h-full' />
);
})
};
export default Carousel;
-85
View File
@@ -1,85 +0,0 @@
'use client';
import { Dispatch, SetStateAction, useRef, useState } from 'react';
import useFilters from '@/app/(site)/useFilters';
import { Card } from '@/components/ui/card';
import { Slider } from '@/components/ui/slider';
import { Toggle } from '@/components/ui/toggle';
import useUrlToMagnet from '@/hooks/useUrlToMagnet';
import useGenres from './useGenres';
export default function Filter() {
useUrlToMagnet();
const { filters, setFilters } = useFilters();
const { data: genres, isFetched } = useGenres();
const [years, setYears] = useState(filters.year || ['1990', new Date().getFullYear().toString()]);
const [scores, setScores] = useState(filters.score || ['0', '10']);
const timeout = useRef<NodeJS.Timeout>();
const handleChangeGenre = (id: number) => () => {
const genreId = id.toString();
setFilters({
name: 'genres',
value: filters.genres?.includes(genreId)
? filters.genres.filter((id) => id !== genreId)
: [...(filters.genres || []), genreId]
});
};
const handleDebouncedChange =
(setter: Dispatch<SetStateAction<Array<string>>>, key: keyof Filters) => (value: Array<number>) => {
clearTimeout(timeout.current);
timeout.current = setTimeout(() => setFilters({ name: key, value: value.map((value) => value.toString()) }), 300);
setter(value.map((value) => value.toString()));
};
if (!isFetched) return;
return (
<>
<Card className='mb-2'>
<ul className='flex gap-2 overflow-auto no-scrollbar'>
{genres?.map((genre) => (
<li key={genre.id}>
<Toggle
data-state={filters.genres?.includes(genre.id.toString()) ? 'on' : 'off'}
onClick={handleChangeGenre(genre.id)}
className='whitespace-nowrap'
>
{genre.name}
</Toggle>
</li>
))}
</ul>
</Card>
<div className='flex w-full my-4 gap-6 flex-wrap'>
<div className='grow flex items-center basis-[250px]'>
<Slider
onValueChange={handleDebouncedChange(setYears, 'year')}
value={years.map((value) => parseInt(value))}
min={1960}
max={new Date().getFullYear()}
step={1}
/>
</div>
<div className='grow flex items-center basis-[250px]'>
<Slider
onValueChange={handleDebouncedChange(setScores, 'score')}
value={scores.map((value) => parseInt(value))}
min={0}
max={10}
step={1}
/>
</div>
</div>
</>
);
}
-45
View File
@@ -1,45 +0,0 @@
'use client';
import { useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';
import { SlidersHorizontal } from 'lucide-react';
import { Button } from '@/components/ui/button';
import useMounted from '@/hooks/useMounted';
import { genres } from '@/lib/api';
import getQueryClient from '@/lib/queryClient';
import Filter from './Filter';
const isShowFilterAtom = atomWithStorage('is-show-filters', false);
export default function FilterToggle() {
const [isShowFilter, setIsShowFilter] = useAtom(isShowFilterAtom);
const isMounted = useMounted();
useEffect(() => {
const queryClient = getQueryClient();
queryClient.prefetchQuery({ queryKey: ['genres'], queryFn: () => genres() });
}, []);
return (
<>
{isShowFilter && <Filter />}
{isMounted &&
createPortal(
<Button
className='p-2'
onClick={() => setIsShowFilter((isShow) => !isShow)}
title={isShowFilter ? 'Hide filters' : 'Show filters'}
variant='ghost'
>
<SlidersHorizontal size={19} />
</Button>,
document.getElementById('actions')!
)}
</>
);
}
-14
View File
@@ -1,14 +0,0 @@
'use client';
import { useQuery } from '@tanstack/react-query';
import { genres } from '@/lib/api';
const useGenres = () => {
return useQuery({
queryKey: ['genres'],
queryFn: () => genres()
});
};
export default useGenres;
-45
View File
@@ -1,45 +0,0 @@
'use client';
import { FC, useState } from 'react';
import Marquee from '@/components/Marquee';
import Nav from '@/components/ui/nav';
import useTrending from './useTrending';
const tabs = [
{
title: 'Trending',
type: 'trending'
},
{
title: 'Streaming',
type: 'streaming'
},
{
title: 'In theaters',
type: 'theater'
}
];
const Trending: FC = () => {
const [active, setActive] = useState(tabs[0]);
const isMobile = typeof window === 'undefined' ? true : matchMedia('(max-width: 600px)').matches;
const { data: trending, isFetched } = useTrending({ type: 'trending', enabled: !isMobile });
const { data: streaming } = useTrending({ type: 'streaming', enabled: !isMobile });
const { data: theater } = useTrending({ type: 'theater', enabled: !isMobile });
const movies = { trending, streaming, theater }[active.type] || [];
return (
isFetched && (
<div>
<Nav tabs={tabs} active={active} onChange={(active) => setActive(active)} className='mb-3' />
<Marquee key={active.type} movies={movies} />
</div>
)
);
};
export default Trending;
@@ -1,13 +0,0 @@
import { useQuery } from '@tanstack/react-query';
import { popularByType, trendingMovies } from '@/lib/api';
const useTrending = ({ type, enabled }: { enabled?: boolean; type: 'trending' | 'streaming' | 'theater' | 'rent' }) => {
return useQuery({
enabled,
queryKey: ['trending', type],
queryFn: () => (type === 'trending' ? trendingMovies() : popularByType({ type }))
});
};
export default useTrending;
+15 -33
View File
@@ -1,35 +1,17 @@
'use client';
import Random from '@/components/Random';
import Trending from '@/components/Trending';
import Preview from '@/components/Movie/Preview';
import Carousel from './components/Carousel';
import Trending from './components/Trending';
import useRandomMovie from './useRandomMovie';
const Random = () => {
const { movies, movie, index, onIndexChange, fetchNextPage } = useRandomMovie();
return (
<Preview
movie={movie}
className='bg-background rounded-md'
card={<Carousel index={index} movies={movies} onIndexChange={onIndexChange} onEndReached={fetchNextPage} />}
/>
);
};
export default function Container() {
return (
<div className='flex flex-col flex-1'>
<div className='xs:mb-4'>
<Random />
<div className='w-full h-2' />
</div>
<div className='xs:block hidden w-full rounded-lg'>
<Trending />
<div className='w-full h-2' />
</div>
const Container = () => (
<div className='flex flex-col flex-1'>
<div className='xs:mb-4'>
<Random />
<div className='w-full h-2' />
</div>
);
}
<div className='xs:block hidden w-full rounded-lg'>
<Trending />
<div className='w-full h-2' />
</div>
</div>
);
export default Container;
+8 -5
View File
@@ -1,19 +1,22 @@
'use client';
import useFavorites from '@/app/(site)/favorites/useFavorites';
import List from '@/components/Movie/List';
import List from '@/components/List';
import useMounted from '@/hooks/useMounted';
import useFavorites from './useFavorites';
export default function Container() {
const { pages } = useFavorites();
const { shows } = useFavorites();
const isMounted = useMounted();
if (isMounted && !pages[0]?.results?.length)
if (!isMounted) return null;
if (!shows.length)
return (
<div className='h-40 w-full flex items-center text-center justify-center text-xl text-muted-foreground'>
There are no items in your favorites list
</div>
);
return <List pages={pages} />;
return <List shows={shows} />;
}
+4 -4
View File
@@ -8,8 +8,8 @@ export const metadata: Metadata = {
'View your favorite shows on Movie Advisor. Keep track of films you’ve added and revisit your top picks anytime.'
};
export const revalidate = 3600;
export default function Favorites() {
const Favorites = () => {
return <Container />;
}
};
export default Favorites;
+12 -23
View File
@@ -1,41 +1,30 @@
import { atom, useAtomValue, useSetAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';
const favoritesAtom = atomWithStorage<Array<MovieDBResponse>>('favorite', [
{ page: 1, results: [], total_pages: 1, total_results: 0 }
]);
const favoritesAtom = atomWithStorage<Show[]>('favorite', [], undefined, {
unstable_getOnInit: true
});
const favoritesMapAtom = atom((get) => {
const map = new Map();
const favorites = get(favoritesAtom);
favorites[0].results.forEach((movie) => map.set(movie.id, movie));
favorites.forEach((show) => map.set(show.id, show));
return map as Map<number, Movie>;
return map as Map<Show['id'], Show>;
});
const useFavorites = () => {
return {
pages: useAtomValue(favoritesAtom),
shows: useAtomValue(favoritesAtom),
map: useAtomValue(favoritesMapAtom)
};
};
export const useFavoritesMutation = () => {
const setFavorites = useSetAtom(favoritesAtom);
const add = (movie: Movie) => {
setFavorites((favorites) => {
favorites[0].results = [movie, ...favorites[0].results];
favorites[0].total_results = favorites[0].results.length;
return [...favorites];
});
};
const remove = (movieId: number) => {
setFavorites((favorites) => {
favorites[0].results = favorites[0].results.filter((movie) => movie.id !== movieId);
favorites[0].total_results = favorites[0].results.length;
return [...favorites];
});
};
const add = (show: Show) => setFavorites((favorites) => [show, ...favorites]);
const remove = (showId: number) => setFavorites((favorites) => favorites.filter(({ id }) => id !== showId));
return {
add,
@@ -43,13 +32,13 @@ export const useFavoritesMutation = () => {
};
};
export const useFavoriteToggle = (movie: Movie) => {
export const useFavoriteToggle = (show: Show) => {
const { add, remove } = useFavoritesMutation();
const { map } = useFavorites();
const isFavorite = map.has(movie.id);
const isFavorite = map.has(show.id);
const toggle = () => (isFavorite ? remove(movie.id) : add(movie));
const toggle = () => (isFavorite ? remove(show.id) : add(show));
return { isFavorite, toggle };
};
+8 -8
View File
@@ -1,11 +1,11 @@
import { Loader } from 'lucide-react';
export default function Loading() {
return (
<div className='w-full min-h-[70vh] flex items-center justify-center'>
<div className='animate-spin'>
<Loader />
</div>
const Loading = () => (
<div className='w-full min-h-[70vh] flex items-center justify-center'>
<div className='animate-spin'>
<Loader />
</div>
);
}
</div>
);
export default Loading;
+5 -3
View File
@@ -1,11 +1,11 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { randomMovies } from '@/lib/api';
import { randomMovies } from '@/api';
import getQueryClient from '@/lib/queryClient';
import Container from './container';
export default async function Random() {
const Random = async () => {
const queryClient = getQueryClient();
await queryClient.prefetchInfiniteQuery({
@@ -19,4 +19,6 @@ export default async function Random() {
<Container />
</HydrationBoundary>
);
}
};
export default Random;
+10 -14
View File
@@ -1,20 +1,16 @@
'use client';
import List from '@/components/Movie/List';
import List from '@/components/List';
import NoResults from '@/components/NoResults';
import usePopular from './usePopular';
export default function Container() {
const { data: top, hasNextPage, fetchNextPage, isFetched } = usePopular();
const Container = () => {
const { shows, fetchNextPage, isFetched } = usePopular();
return (
<>
<List pages={top?.pages || []} fetchNextPage={fetchNextPage} hasNextPage={hasNextPage} />
{isFetched && !top?.pages?.[0]?.results?.length && (
<div className='h-40 w-full flex items-center justify-center text-xl text-muted-foreground'>
Nothing was found
</div>
)}
</>
);
}
if (isFetched && !shows.length) return <NoResults />;
return <List shows={shows} fetchNextPage={fetchNextPage} />;
};
export default Container;
+5 -5
View File
@@ -1,7 +1,7 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { Metadata } from 'next';
import { popularMovies } from '@/lib/api';
import { popularMovies } from '@/api';
import getQueryClient from '@/lib/queryClient';
import Container from './container';
@@ -12,9 +12,7 @@ export const metadata: Metadata = {
'Check out the most popular movies right now on Movie Advisor. See what’s trending and don’t miss out on the latest hits.'
};
export const revalidate = 3600;
export default async function Popular() {
const Popular = async () => {
const queryClient = getQueryClient();
await queryClient.prefetchInfiniteQuery({
@@ -28,4 +26,6 @@ export default async function Popular() {
<Container />
</HydrationBoundary>
);
}
};
export default Popular;
+3 -18
View File
@@ -1,23 +1,8 @@
'use client';
import { useInfiniteQuery } from '@tanstack/react-query';
import { popularMovies } from '@/api';
import useInfiniteList from '@/hooks/useInfiniteList';
import { popularMovies } from '@/lib/api';
const usePopular = () => {
return useInfiniteQuery({
queryKey: ['popular'],
queryFn: ({ pageParam }) => {
return popularMovies({ page: pageParam as string });
},
getNextPageParam(lastPage) {
const { page, total_pages } = lastPage as { page: number; total_pages: number };
if (page === total_pages) return undefined;
return `${page + 1}`;
},
initialPageParam: '1'
});
};
const usePopular = () => useInfiniteList({ queryKey: ['popular'], queryFn: popularMovies });
export default usePopular;
+13 -14
View File
@@ -2,32 +2,31 @@
import { useSearchParams } from 'next/navigation';
import List from '@/components/Movie/List';
import List from '@/components/List';
import NoResults from '@/components/NoResults';
import useSimilar from './useSimilar';
export default function Container() {
const Container = () => {
const params = useSearchParams();
const title = params.get('title');
const type = params.get('type');
const movieId = params.get('movieId') || undefined;
const title = params.get('title') as string;
const showId = params.get('id') as string;
const showType = params.get('type') as Show['type'];
const { data: top, hasNextPage, fetchNextPage, isFetched } = useSimilar({ movieId, type: type as ShowType });
const { shows, fetchNextPage, isFetched } = useSimilar({ showId, showType });
return (
<>
{Boolean(title) && (
<span className='inline-flex w-full h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground mb-2'>
Similar: {decodeURIComponent(title || '')}
Similar: {decodeURIComponent(title)}
</span>
)}
<List type={type as ShowType} pages={top?.pages || []} fetchNextPage={fetchNextPage} hasNextPage={hasNextPage} />
{isFetched && !top?.pages?.[0]?.results?.length && (
<div className='h-40 w-full flex items-center justify-center text-xl text-muted-foreground'>
Nothing was found
</div>
)}
<List shows={shows} fetchNextPage={fetchNextPage} />
{isFetched && !shows.length && <NoResults />}
</>
);
}
};
export default Container;
+7 -7
View File
@@ -1,18 +1,18 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { similarMovies } from '@/lib/api';
import { similarShows } from '@/api';
import getQueryClient from '@/lib/queryClient';
import Container from './container';
export default async function Similar({ searchParams }: { searchParams: Record<string, string> }) {
const Similar = async ({ searchParams }: { searchParams: Record<string, string> }) => {
const queryClient = getQueryClient();
const { movieId, type } = searchParams || {};
const { id, type } = searchParams || {};
await queryClient.prefetchInfiniteQuery({
queryKey: ['similar', movieId, type],
queryFn: () => similarMovies({ movieId, type: type as ShowType }),
queryKey: ['similar', id, type],
queryFn: () => similarShows({ showId: id, showType: type as Show['type'] }),
initialPageParam: '1'
});
@@ -21,6 +21,6 @@ export default async function Similar({ searchParams }: { searchParams: Record<s
<Container />
</HydrationBoundary>
);
}
};
export const revalidate = 3600;
export default Similar;
+11 -17
View File
@@ -1,24 +1,18 @@
'use client';
import { useInfiniteQuery } from '@tanstack/react-query';
import { similarShows } from '@/api';
import useInfiniteList from '@/hooks/useInfiniteList';
import { similarMovies } from '@/lib/api';
interface Props {
showId: string;
showType: Show['type'];
}
const useSimilar = ({ movieId, type = 'movie' }: { movieId?: string; type?: ShowType }) => {
return useInfiniteQuery({
queryKey: ['similar', movieId, type],
enabled: Boolean(movieId),
queryFn: ({ pageParam }) => {
return similarMovies({ page: pageParam as string, movieId, type });
},
getNextPageParam(lastPage) {
const { page, total_pages } = lastPage as { page: number; total_pages: number };
if (page === total_pages) return undefined;
return `${page + 1}`;
},
initialPageParam: '1'
const useSimilar = ({ showId, showType = 'movie' }: Props) =>
useInfiniteList({
enabled: Boolean(showId),
queryKey: ['similar', showId, showType],
queryFn: ({ page }) => similarShows({ page, showId, showType })
});
};
export default useSimilar;
+11 -12
View File
@@ -2,17 +2,18 @@
import { useSearchParams } from 'next/navigation';
import List from '@/components/Movie/List';
import List from '@/components/List';
import NoResults from '@/components/NoResults';
import useStarring from './useStarring';
export default function Container() {
const Container = () => {
const params = useSearchParams();
const title = params.get('title');
const actorId = params.get('actorId') || undefined;
const title = params.get('title') as string;
const actorId = params.get('actorId') as string;
const { data: top, hasNextPage, fetchNextPage, isFetched } = useStarring({ actorId });
const { shows, fetchNextPage, isFetched } = useStarring({ actorId });
return (
<>
@@ -21,12 +22,10 @@ export default function Container() {
Starring: {decodeURIComponent(title || '')}
</span>
)}
<List pages={top?.pages || []} fetchNextPage={fetchNextPage} hasNextPage={hasNextPage} />
{isFetched && !top?.pages?.[0]?.results?.length && (
<div className='h-40 w-full flex items-center justify-center text-xl text-muted-foreground'>
Nothing was found
</div>
)}
<List shows={shows} fetchNextPage={fetchNextPage} />
{isFetched && !shows.length && <NoResults />}
</>
);
}
};
export default Container;
+1 -1
View File
@@ -1,6 +1,6 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { topMovies } from '@/lib/api';
import { topMovies } from '@/api';
import getQueryClient from '@/lib/queryClient';
import Container from './container';
+7 -16
View File
@@ -1,24 +1,15 @@
'use client';
import { useInfiniteQuery } from '@tanstack/react-query';
import { topMovies } from '@/api';
import useInfiniteList from '@/hooks/useInfiniteList';
import { topMovies } from '@/lib/api';
const useStarring = ({ actorId }: { actorId?: string }) => {
return useInfiniteQuery({
const useStarring = ({ actorId }: { actorId?: string }) =>
useInfiniteList({
queryKey: ['starring', actorId],
enabled: Boolean(actorId),
queryFn: ({ pageParam }) => {
return topMovies({ page: pageParam as string, starring: actorId });
},
getNextPageParam(lastPage) {
const { page, total_pages } = lastPage as { page: number; total_pages: number };
if (page === total_pages) return undefined;
return `${page + 1}`;
},
initialPageParam: '1'
queryFn: ({ page }) => {
return topMovies({ page, starring: actorId });
}
});
};
export default useStarring;
+10 -14
View File
@@ -1,20 +1,16 @@
'use client';
import List from '@/components/Movie/List';
import List from '@/components/List';
import NoResults from '@/components/NoResults';
import useTop from './useTop';
export default function Container() {
const { data: top, hasNextPage, fetchNextPage, isFetched } = useTop();
const Container = () => {
const { shows, fetchNextPage, isFetched } = useTop();
return (
<>
<List pages={top?.pages || []} fetchNextPage={fetchNextPage} hasNextPage={hasNextPage} />
{isFetched && !top?.pages?.[0]?.results?.length && (
<div className='h-40 w-full flex items-center justify-center text-xl text-muted-foreground'>
Nothing was found
</div>
)}
</>
);
}
if (isFetched && !shows.length) return <NoResults />;
return <List shows={shows} fetchNextPage={fetchNextPage} />;
};
export default Container;
+5 -5
View File
@@ -1,7 +1,7 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { Metadata } from 'next';
import { topMovies } from '@/lib/api';
import { topMovies } from '@/api';
import getQueryClient from '@/lib/queryClient';
import Container from './container';
@@ -12,9 +12,7 @@ export const metadata: Metadata = {
'Discover the top-rated movies on Movie Advisor. Find the highest-rated films and make informed viewing choices.'
};
export const revalidate = 3600;
export default async function Top() {
const Top = async () => {
const queryClient = getQueryClient();
await queryClient.prefetchInfiniteQuery({
@@ -28,4 +26,6 @@ export default async function Top() {
<Container />
</HydrationBoundary>
);
}
};
export default Top;
+3 -18
View File
@@ -1,23 +1,8 @@
'use client';
import { useInfiniteQuery } from '@tanstack/react-query';
import { topMovies } from '@/api';
import useInfiniteList from '@/hooks/useInfiniteList';
import { topMovies } from '@/lib/api';
const useTop = () => {
return useInfiniteQuery({
queryKey: ['top'],
queryFn: ({ pageParam }) => {
return topMovies({ page: pageParam as string });
},
getNextPageParam(lastPage) {
const { page, total_pages } = lastPage as { page: number; total_pages: number };
if (page === total_pages) return undefined;
return `${page + 1}`;
},
initialPageParam: '1'
});
};
const useTop = () => useInfiniteList({ queryKey: ['top'], queryFn: topMovies });
export default useTop;
-13
View File
@@ -1,13 +0,0 @@
import { useQuery } from '@tanstack/react-query';
import { credits } from '@/lib/api';
const useCredits = ({ movieId, type }: { movieId?: Movie['id']; type?: ShowType }) => {
return useQuery({
queryKey: ['credits', movieId, type],
queryFn: () => credits({ movieId: movieId!, type }),
enabled: Boolean(movieId)
});
};
export default useCredits;
-28
View File
@@ -1,28 +0,0 @@
'use client';
import { useMemo } from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { mapFilters } from '@/lib/utils';
const useFilters = () => {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const filters = useMemo(() => Object.fromEntries(searchParams.entries()), [searchParams]);
const setFilters = ({ name, value }: { name: string; value: string[] }) => {
const search = Object.entries({ ...filters, [name]: value })
.filter(([_, value]) => value?.length)
.map(([key, value]) => `${key}=${value}`)
.join('&');
router.replace(`${pathname}?${search}`);
};
return {
filters: useMemo(() => mapFilters(filters), [filters]),
setFilters
};
};
export default useFilters;
-49
View File
@@ -1,49 +0,0 @@
'use client';
import { startTransition, useCallback, useMemo, useState } from 'react';
import { useInfiniteQuery } from '@tanstack/react-query';
import useSessionRef from '@/hooks/useSessionRef';
import { randomMovies } from '@/lib/api';
const useRandomMovie = () => {
const [indexRef, setIndexRef] = useSessionRef('random-movie-index', 0);
const [index, setIndex] = useState(indexRef.current);
const { data, fetchNextPage } = useInfiniteQuery({
queryKey: ['random-movie'],
queryFn: () => randomMovies(),
getNextPageParam: () => '',
initialPageParam: ''
});
const movies = useMemo(
() =>
data?.pages.reduce((movies, page) => {
movies.push(...page);
return movies;
}, []),
[data]
);
if (movies?.length && !movies[index]) {
setIndex(0);
setIndexRef(0);
}
return {
index,
movies,
movie: movies?.[index],
fetchNextPage,
onIndexChange: useCallback(
(index: number) => {
setIndexRef(index);
startTransition(() => setIndex(index));
},
[setIndexRef]
)
};
};
export default useRandomMovie;
-27
View File
@@ -1,27 +0,0 @@
import { useQuery } from '@tanstack/react-query';
import { Sort } from '@/lib/api/parsers';
const useTorrents = ({
query,
sort,
id,
type,
key,
queryFn
}: {
type: ShowType;
key: string;
id: number;
query: string;
sort: Sort;
queryFn: (params: { query: string; sort: Sort; id: number; type: ShowType }) => Promise<Torrent[]>;
}) => {
return useQuery({
enabled: Boolean(query),
queryKey: [key, query, sort, id, type],
queryFn: () => queryFn({ query, sort, id, type })
});
};
export default useTorrents;
-17
View File
@@ -1,17 +0,0 @@
import { useQuery } from '@tanstack/react-query';
import { trailers } from '@/lib/api';
const useTrailer = ({ movieId, type = 'movie' }: { movieId?: number; type?: ShowType }) => {
return useQuery({
enabled: Boolean(movieId),
queryKey: ['trailers', movieId, type],
queryFn: () => trailers({ movieId: movieId!, type }),
select(trailers) {
const trailer = trailers[0];
return trailer?.site === 'YouTube' ? trailer : null;
}
});
};
export default useTrailer;