fix: random movie index preservation
This commit is contained in:
1 parent
9dc731299f
commit
9e4e1d62fd
7 files changed
+78
-74
No files matched your search
@@ -1,30 +1,23 @@
|
||||
'use client';
|
||||
|
||||
import { forwardRef, useEffect, useLayoutEffect, useRef } from 'react';
|
||||
import { StateSnapshot, Virtuoso, VirtuosoHandle, VirtuosoProps } from 'react-virtuoso';
|
||||
import { Virtuoso, VirtuosoHandle, VirtuosoProps } from 'react-virtuoso';
|
||||
|
||||
import Card from '@/components/Movie/Card';
|
||||
|
||||
let snapshot: StateSnapshot;
|
||||
|
||||
const Carousel = ({
|
||||
index,
|
||||
movies,
|
||||
onIndexChange
|
||||
onIndexChange,
|
||||
onEndReached
|
||||
}: {
|
||||
index: number;
|
||||
movies?: Movie[];
|
||||
onIndexChange: (index: number) => void;
|
||||
onEndReached: () => void;
|
||||
}) => {
|
||||
const ref = useRef<VirtuosoHandle>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const virtuoso = ref.current;
|
||||
|
||||
if (!virtuoso) return;
|
||||
|
||||
return () => virtuoso.getState((state) => (snapshot = state));
|
||||
}, []);
|
||||
const initialIndex = useRef(index);
|
||||
|
||||
useEffect(() => {
|
||||
const scrollTo = ({ key }: globalThis.KeyboardEvent) => {
|
||||
@@ -52,11 +45,12 @@ const Carousel = ({
|
||||
ref={ref}
|
||||
data={movies}
|
||||
context={onIndexChange}
|
||||
horizontalDirection
|
||||
endReached={onEndReached}
|
||||
initialTopMostItemIndex={initialIndex.current}
|
||||
components={components}
|
||||
horizontalDirection
|
||||
skipAnimationFrameInResizeObserver
|
||||
increaseViewportBy={1000}
|
||||
restoreStateFrom={snapshot}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -6,14 +6,14 @@ import Carousel from './components/Carousel';
|
||||
import useRandomMovie from './useRandomMovie';
|
||||
|
||||
export default function Container() {
|
||||
const { movies, movie, index, onIndexChange } = useRandomMovie();
|
||||
const { movies, movie, index, onIndexChange, fetchNextPage } = useRandomMovie();
|
||||
|
||||
return (
|
||||
<>
|
||||
<Preview
|
||||
movie={movie}
|
||||
className='bg-background rounded-md'
|
||||
card={<Carousel index={index} movies={movies} onIndexChange={onIndexChange} />}
|
||||
card={<Carousel index={index} movies={movies} onIndexChange={onIndexChange} onEndReached={fetchNextPage} />}
|
||||
/>
|
||||
<div className='w-full h-2' />
|
||||
</>
|
||||
|
||||
+5
-1
@@ -8,7 +8,11 @@ import Container from './container';
|
||||
export default async function Random() {
|
||||
const queryClient = getQueryClient();
|
||||
|
||||
await queryClient.prefetchQuery({ queryKey: ['random-movie'], queryFn: () => randomMovies({ filters: {} }) });
|
||||
await queryClient.prefetchInfiniteQuery({
|
||||
queryKey: ['random-movie'],
|
||||
queryFn: () => randomMovies(),
|
||||
initialPageParam: '1'
|
||||
});
|
||||
|
||||
return (
|
||||
<HydrationBoundary state={dehydrate(queryClient)}>
|
||||
|
||||
@@ -1,52 +1,43 @@
|
||||
'use client';
|
||||
|
||||
import { startTransition, useCallback, useState } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { startTransition, useCallback, useMemo, useState } from 'react';
|
||||
import { useInfiniteQuery } from '@tanstack/react-query';
|
||||
|
||||
import useSessionRef from '@/hooks/useSessionRef';
|
||||
import { randomMovies } from '@/lib/api';
|
||||
|
||||
const UPDATE_RATE = 10;
|
||||
|
||||
let previousIndex: number = 0;
|
||||
|
||||
const useRandomMovie = () => {
|
||||
const queryClient = useQueryClient();
|
||||
const [index, setIndex] = useState(previousIndex);
|
||||
const [indexRef, setIndexRef] = useSessionRef('random-movie-index', 0);
|
||||
const [index, setIndex] = useState(indexRef.current);
|
||||
|
||||
const { data: movies, refetch } = useQuery({
|
||||
const { data, fetchNextPage } = useInfiniteQuery({
|
||||
queryKey: ['random-movie'],
|
||||
queryFn: () => randomMovies({ filters: {} }),
|
||||
structuralSharing(_, newData) {
|
||||
const uniqueIds: Record<string, number> = {};
|
||||
const current = queryClient.getQueryData<Movie[]>(['random-movie']) || [];
|
||||
const next = Array.isArray(newData) ? newData : [newData];
|
||||
|
||||
return [...current, ...next].reduce((unique, movie) => {
|
||||
if (uniqueIds[movie.id]) return unique;
|
||||
|
||||
uniqueIds[movie.id] = movie.id;
|
||||
unique.push(movie);
|
||||
|
||||
return unique;
|
||||
}, [] as Movie[]);
|
||||
}
|
||||
queryFn: () => randomMovies(),
|
||||
getNextPageParam: () => '',
|
||||
initialPageParam: ''
|
||||
});
|
||||
|
||||
const movies = useMemo(
|
||||
() =>
|
||||
data?.pages.reduce((movies, page) => {
|
||||
movies.push(...page);
|
||||
return movies;
|
||||
}, []),
|
||||
[data]
|
||||
);
|
||||
|
||||
return {
|
||||
index,
|
||||
movies,
|
||||
movie: movies?.[index],
|
||||
hasPrevious: index > 0,
|
||||
fetchNextPage,
|
||||
onIndexChange: useCallback(
|
||||
(index: number) => {
|
||||
if ((index && index % UPDATE_RATE === 0) || movies!.length < UPDATE_RATE) {
|
||||
refetch();
|
||||
}
|
||||
previousIndex = index;
|
||||
setIndexRef(index);
|
||||
startTransition(() => setIndex(index));
|
||||
},
|
||||
[movies]
|
||||
),
|
||||
index
|
||||
[setIndexRef]
|
||||
)
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
+1
-2
@@ -6,7 +6,6 @@ import { cookies } from 'next/headers';
|
||||
const poppins = Poppins({ subsets: ['latin'], weight: '400' });
|
||||
|
||||
import Header from '@/components/Header';
|
||||
import { cn } from '@/lib/utils';
|
||||
import Providers from '@/providers';
|
||||
|
||||
import '@/styles/index.css';
|
||||
@@ -38,7 +37,7 @@ export default function RootLayout({ children }: { children: ReactNode }) {
|
||||
<div className='sticky top-0 z-20'>
|
||||
<Header />
|
||||
</div>
|
||||
<main className='px-2 max-w-[1240px] mx-auto'>{children}</main>
|
||||
<main className='px-2 mx-auto max-w-[1240px]'>{children}</main>
|
||||
</Providers>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in new issue
Block a user