Last active
December 21, 2020 12:34
-
-
Save ramyareye/b69c02df4f46f00e2f2434fd43e03c0a to your computer and use it in GitHub Desktop.
useSWRInfinite example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {useEffect, useState, useRef} from 'react'; | |
import {useSWRInfinite} from 'swr'; | |
import Layout from 'components/layouts'; | |
import ErrorPage from 'components/Error'; | |
import ActorCard from 'components/actorCard'; | |
import VerticalList from 'components/verticalList'; | |
import gate from 'gate'; | |
import useOnScreen from 'hooks/useOnScreen'; | |
const IranianActors = (props) => { | |
const ref = useRef(); | |
const {cdn = '', last_page = 0} = props?.data?.data || {}; | |
const [casts, setCasts] = useState(props?.data?.data?.casts || []); | |
if (!props.data) { | |
return <ErrorPage exact />; | |
} | |
const isVisible = useOnScreen(ref); | |
const getKey = (pageIndex, previousPageData) => { | |
if ( | |
previousPageData?.data?.casts && | |
!previousPageData?.data?.casts.length | |
) { | |
return null; // reached the end | |
} | |
return `iranainActors_${pageIndex}`; // SWR key | |
}; | |
const {data, size, setSize} = useSWRInfinite( | |
getKey, | |
(key) => { | |
const index = key.split('iranainActors_'); | |
return gate.iranainActors({page: Number(index[1]) + 1}); | |
}, | |
{revalidateAll: false, revalidateOnFocus: false}, | |
); | |
useEffect(() => { | |
data?.map((d) => { | |
if (d?.data?.casts?.length) { | |
const casts_ = d?.data?.casts.filter((c) => { | |
const is = casts.find((cc) => cc.id === c.id); | |
return !is; | |
}); | |
setCasts((oldCasts) => { | |
return [...oldCasts, ...casts_]; | |
}); | |
} | |
}); | |
}, [data]); | |
const hasMore = size < last_page; | |
useEffect(() => { | |
if (isVisible && hasMore) { | |
setSize(size + 1); | |
} | |
}, [isVisible]); | |
return ( | |
<Layout title="بازیگران ایرانی" isShoweCatgory={true}> | |
<div id="actor"> | |
<VerticalList | |
data={casts} | |
renderItem={(cast) => { | |
return ( | |
<ActorCard | |
cdn={cdn} | |
item={cast} | |
width={cast._width} | |
height={cast._height} | |
/> | |
); | |
}} | |
/> | |
<div className="actors_loading" ref={ref}> | |
{casts.length && size < last_page ? 'در حال بارگذاری...' : null} | |
</div> | |
</div> | |
</Layout> | |
); | |
}; | |
export async function getServerSideProps() { | |
let data = null; | |
try { | |
const result = await gate.iranainActors(); | |
data = result; | |
} catch { | |
//logger | |
} | |
return { | |
props: { | |
data, | |
}, | |
}; | |
} | |
export default IranianActors; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment