Last active
November 30, 2020 02:17
-
-
Save wobsoriano/da425cae70afdb410bf3d0674f371195 to your computer and use it in GitHub Desktop.
Fetching Reddit posts with useSWRInfinite
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 { useSWRInfinite } from 'swr'; | |
| const fetcher = (url) => fetch(url).then((res) => res.json()); | |
| const baseUrl = 'https://www.reddit.com'; | |
| export const useRedditPosts = (subreddit, sort = 'hot') => { | |
| if (!subreddit) { | |
| throw new Error('Subreddit is required'); | |
| } | |
| const PAGE_LIMIT = 12; | |
| const url = `${baseUrl}/r/${subreddit}/${sort}.json?raw_json=1`; | |
| const { data, error, size, setSize } = useSWRInfinite((pageIndex, previousPageData) => { | |
| // reached the end | |
| if (previousPageData && !previousPageData.data.after) return null; | |
| // first page, we don't have `previousPageData` | |
| if (pageIndex === 0) return `${url}&limit=${PAGE_LIMIT}`; | |
| // add the cursor to the API endpoint | |
| return `${url}&after=${previousPageData.data.after}&limit=${PAGE_LIMIT}`; | |
| }, fetcher); | |
| const posts = data ? data.map((i) => i.data.children).flat() : []; | |
| const isLoadingInitialData = !data && !error; | |
| const isLoadingMore = size > 0 && data && typeof data[size - 1] === 'undefined'; | |
| const isEmpty = data?.[0]?.length === 0; | |
| const isReachingEnd = isEmpty || (data && !data[data.length - 1]?.data?.after); | |
| return { posts, error, isLoadingInitialData, isLoadingMore, size, setSize, isReachingEnd }; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment