├── .github └── workflows │ └── ci.yaml ├── .gitignore ├── .storybook ├── global.css ├── main.js └── preview.js ├── CHANGELOG.md ├── LICENSE ├── README.md ├── eslint.config.mjs ├── package.json ├── rollup.config.js ├── src ├── assets │ └── .gitkeep ├── components │ ├── InfiniteScroll │ │ ├── GitHub.stories.tsx │ │ ├── LoadingIndicator.css │ │ ├── LoadingIndicator.tsx │ │ ├── Picsum.stories.tsx │ │ ├── Reddit.stories.tsx │ │ └── index.tsx │ └── index.ts └── index.ts ├── tsconfig.json └── yarn.lock /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: push 4 | 5 | jobs: 6 | test-lint-build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v2 10 | - uses: actions/setup-node@v1 11 | with: 12 | node-version: 12 13 | - name: Restore node modules cache 14 | uses: actions/cache@v2 15 | env: 16 | cache-name: cache-node-modules 17 | with: 18 | path: node_modules 19 | key: ${{ runner.os }}-${{ env.cache-name }}-${{ hashFiles('**/yarn.lock') }} 20 | - name: Install Dependencies 21 | run: yarn install 22 | - name: Lint code 23 | run: yarn lint 24 | - name: Build 25 | run: yarn build 26 | 27 | publish: 28 | if: ${{ github.ref == 'refs/heads/main' }} 29 | needs: test-lint-build 30 | runs-on: ubuntu-latest 31 | steps: 32 | - uses: actions/checkout@v2 33 | with: 34 | persist-credentials: false 35 | - uses: actions/setup-node@v1 36 | with: 37 | node-version: 12 38 | - name: Restore node modules cache 39 | uses: actions/cache@v2 40 | env: 41 | cache-name: cache-node-modules 42 | with: 43 | path: node_modules 44 | key: ${{ runner.os }}-${{ env.cache-name }}-${{ hashFiles('**/yarn.lock') }} 45 | - name: Install Dependencies 46 | run: yarn install 47 | - name: Build 48 | run: yarn build 49 | - name: Release 50 | env: 51 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 52 | GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }} 53 | run: npx semantic-release 54 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_STORE 2 | 3 | /dist/ 4 | node_modules 5 | .rpt2_cache 6 | .cache 7 | .env* 8 | 9 | /storybook 10 | 11 | /coverage 12 | 13 | # Ignore npm/yarn debug log 14 | npm-debug.log 15 | yarn-error.log 16 | 17 | # storybook 18 | .out 19 | 20 | /coverage -------------------------------------------------------------------------------- /.storybook/global.css: -------------------------------------------------------------------------------- 1 | @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap'); 2 | 3 | * { 4 | font-family: 'Roboto', sans-serif; 5 | box-sizing: border-box; 6 | } 7 | -------------------------------------------------------------------------------- /.storybook/main.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | stories: ['../src/**/*.stories.tsx'], 3 | framework: '@storybook/react-vite', 4 | typescript: { 5 | reactDocgen: 'react-docgen-typescript' 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /.storybook/preview.js: -------------------------------------------------------------------------------- 1 | import './global.css'; 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ### [1.0.1](https://github.com/esinx/react-swr-infinite-scroll/compare/v1.0.0...v1.0.1) (2021-07-14) 4 | 5 | 6 | ### Features 7 | 8 | * **docs:** host storybook ([8346093](https://github.com/esinx/react-swr-infinite-scroll/commit/83460934179d969d4fa76dc467761c1c49cb81f9)) 9 | 10 | 11 | ### Bug Fixes 12 | 13 | * export the component explicitly ([816a8f7](https://github.com/esinx/react-swr-infinite-scroll/commit/816a8f780e4f6f5cb925ec0a04c06539ab22afd9)) 14 | 15 | ## 1.0.0 (2021-07-07) 16 | 17 | 18 | ### Features 19 | 20 | * **props:** optional loading indicator ([73b8c82](https://github.com/esinx/react-swr-infinite-scroll/commit/73b8c82b212831335b1772f0ad41a79d7f08a0da)) 21 | 22 | ### [1.0.0] 23 | 24 | - Initial release 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2024 Eunsoo Shin (esinx) 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SWR Infinite Scroll 2 | 3 | [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release) 4 | 5 | > An easier way to `useSWRInfinite` 6 | 7 | SWR provides an amazing way to manage paged data through `useSWRInfinite`. But it's not as intuitive when it comes to implementing infinite scroll itself. `react-swr-infinite-scroll` attempts to solve this by implementing it for you. Using the `IntersectionObserver` API, it detects whether the viewport has reached the _end of the list view_ to decide if the data has to be reloaded. 8 | 9 | ## Demo 10 | 11 | Visit the demo storybook [here](https://react-swr-infinite-scroll.vercel.app/). 12 | 13 | ## Features 14 | 15 | - Seamless useSWRInfinite integration 16 | - Awesome TypeScript completion 17 | - InfiniteScroll (of course) 18 | - Horizontal InfiniteScroll 19 | - Customizable loading & ending indicator 20 | - Customizable triggering behavior (offset) 21 | 22 | ## Installation 23 | 24 | ```shell 25 | yarn add react-swr-infinite-scroll 26 | ``` 27 | or 28 | ```shell 29 | npm install --save react-swr-infinite-scroll 30 | ``` 31 | 32 | ## Usage 33 | 34 | > tldr; You will still `useSWRInfinite`, while the state management is done by the `InfiniteScroll` component in the render 35 | 36 | What you'll need to implement/know: 37 | - Some way to **load paged data** 38 | - Some way to load the **next paged data** 39 | - Some way to **detect** that the paged data is **reaching its end** 40 | - Some way to **render** the list of paged data 41 | 42 | ```jsx 43 | const Component: React.FC = () => { 44 | const swr = useSWRInfinite(/* implement SWR here*/) 45 | return 49 | {response => /* implement render here */} 50 | 51 | } 52 | ``` 53 | 54 | ### Props 55 | 56 | ```typescript 57 | type Props = { 58 | swr: SWRInfiniteResponse; 59 | children: React.ReactChild | ((item: T) => React.ReactNode); 60 | loadingIndicator?: React.ReactNode; 61 | endingIndicator?: React.ReactNode; 62 | isReachingEnd: boolean | ((swr: SWRInfiniteResponse) => boolean); 63 | offset?: number; 64 | }; 65 | ``` 66 | 67 | - `swr`: pass your `useSWRInfinite` hook here 68 | - `children`: could either be a regular react child that uses the data from the original swr object itself, or a function that renders the list items passed from the `InfiniteScroll` component 69 | - `isReachingEnd`: A function / boolean value to tell if the list is reaching its end (see examples for a better idea of how `isReachingEnd` should be implemented) 70 | - (optional) `loadingIndicator`: A react node to be displayed when the list is loading 71 | - (optional) `endingIndicator`: A react node to be displayed when the list is reaching its end 72 | - (optional) `offset` 73 | - if set to a positive value, the reload trigger will be called when the end of the list is behind the viewport 74 | - if set to a negative value, the reload trigger will be called when the end of the list is ahead of the viewport 75 | 76 | ## Examples 77 | 78 | ### GitHub Issues 79 | 80 | Borrowed from [this example](https://swr.vercel.app/examples/infinite-loading) by SWR 81 | 82 | ```jsx 83 | 84 | const PAGE_SIZE = 5; 85 | 86 | export const GitHub: React.FC = () => { 87 | 88 | const swr = useSWRInfinite( 89 | (index, prev) => 90 | `https://api.github.com/repos/reactjs/react-a11y/issues?per_page=${PAGE_SIZE}&page=${ 91 | index + 1 92 | }`, 93 | { 94 | fetcher: async (key) => fetch(key).then((res) => res.json()), 95 | } 96 | ); 97 | 98 | return ( 99 |
100 | 105 | swr.data?.[0]?.length === 0 || swr.data?.[swr.data?.length - 1]?.length < PAGE_SIZE 106 | } 107 | > 108 | {(response) => 109 | response?.map((issue) => ( 110 |
119 |
{issue.title}
120 |
121 | {issue.user.login} • {new Date(issue.created_at).toDateString()} 122 |
123 |
124 | )) 125 | } 126 |
127 |
128 | ); 129 | }; 130 | ``` 131 | 132 | More examples can be found in the storybook documentation. You can clone this repo locally and run 133 | ```shell 134 | yarn 135 | yarn storybook 136 | ``` 137 | to view them 138 | 139 | ## Feedback 140 | 141 | Issues and pull requests are welcome! Feel free to leave any major/minor feedback through the repo page. 142 | 143 | ## License 144 | 145 | > It's MIT as usual 146 | 147 | Copyright 2023 Eunsoo Shin (esinx) 148 | 149 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 150 | 151 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 152 | 153 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 154 | 155 | -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | import config from "@esinx/eslint-config"; 2 | 3 | export default [ 4 | ...config, 5 | ] -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-swr-infinite-scroll", 3 | "license": "MIT", 4 | "version": "2.0.0", 5 | "private": false, 6 | "description": "Infinite scrolling with useSWRInfinite", 7 | "author": "Eunsoo Shin", 8 | "prettier": "@esinx/prettier-config", 9 | "homepage": "https://github.com/esinx/react-swr-infinite-scroll", 10 | "bugs": { 11 | "url": "https://github.com/esinx/react-swr-infinite-scroll/issues" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "git+https://github.com/esinx/react-swr-infinite-scroll.git" 16 | }, 17 | "keywords": [ 18 | "react", 19 | "swr", 20 | "infinite scroll", 21 | "hooks" 22 | ], 23 | "scripts": { 24 | "build": "yarn clean; rollup -c", 25 | "clean": "rimraf dist", 26 | "dev": "yarn storybook", 27 | "format": "prettier --write \"src/**/*.{ts,tsx,json,js,jsx}\"", 28 | "format:check": "prettier --list-different \"src/**/*.{ts,tsx,json,js,jsx}\"", 29 | "lint": "yarn lint:script", 30 | "lint:script": "eslint ./src", 31 | "storybook": "storybook dev --port 9001 -c .storybook", 32 | "build:storybook": "storybook build -c .storybook -o storybook", 33 | "publish": "npx semantic-release --no-ci" 34 | }, 35 | "main": "index.js", 36 | "module": "index.esm.js", 37 | "types": "index.d.ts", 38 | "peerDependencies": {}, 39 | "devDependencies": { 40 | "@babel/core": "^7.12.7", 41 | "@esinx/eslint-config": "^2.0.1", 42 | "@esinx/prettier-config": "^1.0.0-3", 43 | "@rollup/plugin-commonjs": "^16.0.0", 44 | "@rollup/plugin-node-resolve": "^10.0.0", 45 | "@semantic-release/changelog": "^5.0.1", 46 | "@semantic-release/commit-analyzer": "^8.0.1", 47 | "@semantic-release/git": "^9.0.0", 48 | "@semantic-release/npm": "^7.0.8", 49 | "@semantic-release/release-notes-generator": "^9.0.1", 50 | "@storybook/react-vite": "^8.1.11", 51 | "@types/node": "^12", 52 | "babel-loader": "^8.2.1", 53 | "conventional-changelog-conventionalcommits": "^4.4.0", 54 | "eslint": "^9.6.0", 55 | "prettier": "^2.2.0", 56 | "react": "^18.3.1", 57 | "react-dom": "^18.3.1", 58 | "rimraf": "^3.0.2", 59 | "rollup": "^2.33.3", 60 | "rollup-plugin-copy": "^3.3.0", 61 | "rollup-plugin-terser": "7.0.2", 62 | "rollup-plugin-typescript2": "^0.36.0", 63 | "semantic-release": "^17.3.0", 64 | "storybook": "^8.1.11", 65 | "style-loader": "^2.0.0", 66 | "swr": "^0.5.6", 67 | "ts-loader": "^8.0.11", 68 | "typescript": "^5.5.3", 69 | "vite": "^5.3.3" 70 | }, 71 | "release": { 72 | "branches": [ 73 | "main", 74 | "next" 75 | ], 76 | "preset": "conventionalcommits", 77 | "plugins": [ 78 | [ 79 | "@semantic-release/commit-analyzer", 80 | { 81 | "releaseRules": [ 82 | { 83 | "type": "revert", 84 | "release": "patch" 85 | }, 86 | { 87 | "type": "build", 88 | "release": "patch" 89 | } 90 | ] 91 | } 92 | ], 93 | "@semantic-release/release-notes-generator", 94 | [ 95 | "@semantic-release/changelog", 96 | { 97 | "changelogTitle": "# Changelog" 98 | } 99 | ], 100 | [ 101 | "@semantic-release/npm", 102 | { 103 | "pkgRoot": "dist" 104 | } 105 | ], 106 | [ 107 | "@semantic-release/git", 108 | { 109 | "message": "chore(release): ${nextRelease.version} [skip ci]", 110 | "assets": [ 111 | "CHANGELOG.md" 112 | ] 113 | } 114 | ] 115 | ] 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import typescript from 'rollup-plugin-typescript2'; 2 | import { terser } from 'rollup-plugin-terser'; 3 | import commonjs from '@rollup/plugin-commonjs'; 4 | import pkg from './package.json'; 5 | import resolve from '@rollup/plugin-node-resolve'; 6 | import copy from 'rollup-plugin-copy'; 7 | import ts from 'typescript'; 8 | 9 | export default { 10 | input: './src/index.ts', 11 | external: [...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.peerDependencies || {})], 12 | output: [ 13 | { 14 | file: `./dist/${pkg.module}`, 15 | format: 'es', 16 | sourcemap: true, 17 | }, 18 | { 19 | file: `./dist/${pkg.main}`, 20 | format: 'cjs', 21 | exports: 'default', 22 | sourcemap: true, 23 | }, 24 | ], 25 | plugins: [ 26 | resolve(), 27 | commonjs(), 28 | typescript({ 29 | typescript: ts, 30 | tsconfig: 'tsconfig.json', 31 | tsconfigDefaults: { 32 | exclude: [ 33 | '**/*.spec.ts', 34 | '**/*.test.ts', 35 | '**/*.stories.ts', 36 | '**/*.spec.tsx', 37 | '**/*.test.tsx', 38 | '**/*.stories.tsx', 39 | 'node_modules', 40 | 'bower_components', 41 | 'jspm_packages', 42 | 'dist', 43 | ], 44 | compilerOptions: { 45 | sourceMap: true, 46 | declaration: true, 47 | }, 48 | }, 49 | }), 50 | terser({ 51 | output: { 52 | comments: false, 53 | }, 54 | }), 55 | copy({ 56 | targets: [ 57 | { src: 'LICENSE', dest: 'dist' }, 58 | { src: 'README.md', dest: 'dist' }, 59 | { 60 | src: 'package.json', 61 | dest: 'dist', 62 | transform: (content) => { 63 | const { scripts, devDependencies, husky, release, engines, ...keep } = JSON.parse( 64 | content.toString() 65 | ); 66 | return JSON.stringify(keep, null, 2); 67 | }, 68 | }, 69 | ], 70 | }), 71 | ], 72 | }; 73 | -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/esinx/react-swr-infinite-scroll/4ece8e1bc290975724aee6ad27036cc9cb957e27/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/components/InfiniteScroll/GitHub.stories.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import { useSWRInfinite } from 'swr' 3 | 4 | import LoadingIndicator from './LoadingIndicator' 5 | import InfiniteScroll from '.' 6 | 7 | export default { 8 | title: 'InfiniteScroll/GitHub', 9 | component: InfiniteScroll, 10 | } 11 | 12 | export const GitHub: React.FC = () => { 13 | const PAGE_SIZE = 5 14 | 15 | const swr = useSWRInfinite( 16 | index => 17 | `https://api.github.com/repos/reactjs/react-a11y/issues?per_page=${PAGE_SIZE}&page=${ 18 | index + 1 19 | }`, 20 | { 21 | fetcher: async key => fetch(key).then(res => res.json()), 22 | }, 23 | ) 24 | 25 | return ( 26 | } 29 | endingIndicator={ 30 |
31 | No more issues! 🎉 32 |
33 | } 34 | isReachingEnd={swr => 35 | swr.data?.[0]?.length === 0 || 36 | swr.data?.[swr.data?.length - 1]?.length < PAGE_SIZE 37 | } 38 | > 39 | {response => 40 | response?.map(issue => ( 41 |
51 |
{issue.title}
52 |
53 | {issue.user.login} • {new Date(issue.created_at).toDateString()} 54 |
55 |
56 | )) 57 | } 58 |
59 | ) 60 | } 61 | GitHub.storyName = 'GitHub' 62 | -------------------------------------------------------------------------------- /src/components/InfiniteScroll/LoadingIndicator.css: -------------------------------------------------------------------------------- 1 | .loading-indicator { 2 | border: 5px solid #aaa; 3 | width: 30px; 4 | height: 30px; 5 | border-radius: 50%; 6 | border-left-color: transparent; 7 | border-right-color: transparent; 8 | border-bottom-color: transparent; 9 | animation: spin 0.8s linear infinite; 10 | } 11 | 12 | @keyframes spin { 13 | 0% { 14 | transform: rotate(0deg); 15 | } 16 | 100% { 17 | transform: rotate(360deg); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/components/InfiniteScroll/LoadingIndicator.tsx: -------------------------------------------------------------------------------- 1 | import React, { CSSProperties } from 'react' 2 | 3 | import './LoadingIndicator.css' 4 | 5 | const LoadingIndicator: React.FC<{ style?: CSSProperties }> = props => ( 6 |
7 | ) 8 | export default LoadingIndicator 9 | -------------------------------------------------------------------------------- /src/components/InfiniteScroll/Picsum.stories.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import { useSWRInfinite } from 'swr' 3 | 4 | import LoadingIndicator from './LoadingIndicator' 5 | import InfiniteScroll from '.' 6 | 7 | export default { 8 | title: 'InfiniteScroll/Picsum', 9 | component: InfiniteScroll, 10 | parameters: { 11 | layout: 'fullscreen', 12 | }, 13 | } 14 | 15 | interface PicsumItem { 16 | id: string 17 | author: string 18 | width: number 19 | height: number 20 | url: string 21 | download_url: string 22 | } 23 | 24 | type PicsumResponse = PicsumItem[] 25 | 26 | export const Picsum: React.FC = () => { 27 | const PAGE_SIZE = 5 28 | 29 | const swr = useSWRInfinite( 30 | index => 31 | `https://picsum.photos/v2/list?page=${index + 1}&limit=${PAGE_SIZE}`, 32 | { 33 | fetcher: async key => fetch(key).then(res => res.json()), 34 | }, 35 | ) 36 | 37 | return ( 38 |
39 | } 42 | isReachingEnd={swr => 43 | swr.data?.[0]?.length === 0 || 44 | (swr.data?.[swr.data?.length - 1]?.length ?? 0) < PAGE_SIZE 45 | } 46 | > 47 | {response => 48 | response?.map(item => { 49 | return ( 50 |
60 |
74 |
75 | {item.width} x {item.height} 76 |
77 |
78 | {item.author} 79 |
80 |
81 | {item.url} 82 |
83 |
84 |
85 | ) 86 | }) 87 | } 88 |
89 |
90 | ) 91 | } 92 | Picsum.storyName = 'Picsum (Horizontal Scrolling)' 93 | -------------------------------------------------------------------------------- /src/components/InfiniteScroll/Reddit.stories.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import { useSWRInfinite } from 'swr' 3 | 4 | import LoadingIndicator from './LoadingIndicator' 5 | import InfiniteScroll from '.' 6 | 7 | export default { 8 | title: 'InfiniteScroll/Reddit', 9 | component: InfiniteScroll, 10 | } 11 | 12 | interface RedditPost { 13 | subreddit: string 14 | author: string 15 | title: string 16 | thumbnail: string 17 | permalink: string 18 | url: string 19 | } 20 | 21 | interface RedditPostObject { 22 | kind: 't3' 23 | data: RedditPost 24 | } 25 | 26 | interface RedditDataResponse { 27 | after: string 28 | children: RedditPostObject[] 29 | } 30 | 31 | const RedditPostCard: React.FC<{ post: RedditPost }> = ({ post }) => ( 32 |
41 |
42 | {post.subreddit} • {post.author} 43 |
44 |
45 | {post.thumbnail?.startsWith('http') && ( 46 | 56 | )} 57 | 88 |
89 |
90 | ) 91 | 92 | export const Reddit = () => { 93 | const swr = useSWRInfinite( 94 | (index, prev) => 95 | prev 96 | ? `https://www.reddit.com/.json?limit=5&after=${prev.after}` 97 | : 'https://www.reddit.com/.json', 98 | { 99 | fetcher: async key => 100 | fetch(key) 101 | .then(res => res.json()) 102 | .then(json => json?.data), 103 | }, 104 | ) 105 | 106 | return ( 107 | } 110 | isReachingEnd={swr => !swr.data?.[swr.data?.length - 1]?.after ?? false} 111 | > 112 | {response => 113 | response?.children?.map(({ data }) => ( 114 | 115 | )) 116 | } 117 | 118 | ) 119 | } 120 | -------------------------------------------------------------------------------- /src/components/InfiniteScroll/index.tsx: -------------------------------------------------------------------------------- 1 | import React, { Ref, useEffect, useState } from 'react' 2 | import type { SWRInfiniteResponse } from 'swr' 3 | 4 | interface InfiniteScrollProps { 5 | swr: SWRInfiniteResponse 6 | children?: React.ReactChild | ((item: T) => React.ReactNode) 7 | loadingIndicator?: React.ReactNode 8 | endingIndicator?: React.ReactNode 9 | isReachingEnd: boolean | ((swr: SWRInfiniteResponse) => boolean) 10 | offset?: number 11 | } 12 | 13 | const useIntersection = (): [boolean, Ref] => { 14 | const [intersecting, setIntersecting] = useState(false) 15 | const [element, setElement] = useState() 16 | useEffect(() => { 17 | if (!element) return 18 | const observer = new IntersectionObserver(entries => { 19 | setIntersecting(entries[0]?.isIntersecting) 20 | }) 21 | observer.observe(element) 22 | return () => observer.unobserve(element) 23 | }, [element]) 24 | return [intersecting, el => el && setElement(el)] 25 | } 26 | 27 | const InfiniteScroll = ( 28 | props: InfiniteScrollProps, 29 | ): React.ReactElement> => { 30 | const { 31 | swr, 32 | swr: { setSize, data, isValidating }, 33 | children, 34 | loadingIndicator, 35 | endingIndicator, 36 | isReachingEnd, 37 | offset = 0, 38 | } = props 39 | 40 | const [intersecting, ref] = useIntersection() 41 | 42 | const ending = 43 | typeof isReachingEnd === 'function' ? isReachingEnd(swr) : isReachingEnd 44 | 45 | useEffect(() => { 46 | if (intersecting && !isValidating && !ending) { 47 | setSize(size => size + 1) 48 | } 49 | }, [intersecting, isValidating, setSize, ending]) 50 | 51 | return ( 52 | <> 53 | {typeof children === 'function' 54 | ? data?.map(item => children(item)) 55 | : children} 56 |
57 |
58 | {ending ? endingIndicator : loadingIndicator} 59 |
60 | 61 | ) 62 | } 63 | 64 | export default InfiniteScroll 65 | -------------------------------------------------------------------------------- /src/components/index.ts: -------------------------------------------------------------------------------- 1 | // make sure you import all components into this file 2 | 3 | import InfiniteScroll from './InfiniteScroll' 4 | 5 | export default InfiniteScroll 6 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import InfiniteScroll from './components' 2 | export default InfiniteScroll 3 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowSyntheticDefaultImports": true, 4 | "declaration": true, 5 | "esModuleInterop": true, 6 | "experimentalDecorators": true, 7 | "jsx": "react", 8 | "lib": ["dom", "es5"], 9 | "module": "esNext", 10 | "moduleResolution": "node", 11 | "noImplicitAny": false, 12 | "noImplicitReturns": true, 13 | "noUnusedLocals": true, 14 | "noUnusedParameters": false, 15 | "outDir": "./dist", 16 | "pretty": true, 17 | "sourceMap": true, 18 | "strict": true, 19 | "target": "es5" 20 | }, 21 | "exclude": ["node_modules"], 22 | "include": ["./src"] 23 | } 24 | --------------------------------------------------------------------------------