Skip to content

Instantly share code, notes, and snippets.

@antoniomesquita09
Last active March 18, 2021 01:50
Show Gist options
  • Save antoniomesquita09/19fea8fe9339fe09d9f0a0473a9bf25d to your computer and use it in GitHub Desktop.
Save antoniomesquita09/19fea8fe9339fe09d9f0a0473a9bf25d to your computer and use it in GitHub Desktop.
Table infinite scrolling.
import React, { useState, useRef, useCallback, useEffect } from 'react'
// import { api } from 'services/api'
// just for this exemple
const userList = [
{
id: '1',
name: 'Antonio Mesquita',
email: 'antonio.mesquita@ifood.com.br',
},
{
id: '2',
name: 'Antonio Mesquita',
email: 'antonio.mesquita@ifood.com.br',
},
{
id: '3',
name: 'Antonio Mesquita',
email: 'antonio.mesquita@ifood.com.br',
},
]
const Table = () => {
const observer = useRef()
const [users, setUsers] = useState(userList)
const [loading, setLoading] = useState(false)
const [limit, setLimit] = useState(10)
const fetchData = useCallback(
async (currentLimit) => {
setLoading(true)
try {
console.log(currentLimit)
// your data fetch function
// const { data } = await api.get('/users', { params: { limit: currentLimit } })
setUsers([...users, ...userList])
} catch (e) {
console.log(e.message)
}
setLoading(false)
},
[users]
)
useEffect(() => {
fetchData(limit)
}, [limit])
const lastComponentRendered = useCallback(
(node) => {
if (loading) return
if (observer.current) observer.current.disconnect()
observer.current = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
setLimit((limit) => limit + 20)
}
})
if (node) observer.current.observe(node)
},
[loading]
)
const usersLength = users ? users.length : 0
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{users &&
users.map((user, index) => (
<tr
key={index}
ref={usersLength === index + 1 ? lastComponentRendered : null}
>
<td>{user.name || '-'}</td>
<td>{user.email || '-'}</td>
</tr>
))}
</tbody>
</table>
)
}
export default Table
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment