Created
August 4, 2020 09:58
-
-
Save hyber1z0r/33572e706631a1b2d767c62d20059780 to your computer and use it in GitHub Desktop.
useWhenVisible example
This file contains 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 useWhenVisible from './useWhenVisible'; | |
const TodoList = () => { | |
const limit = 25; | |
const [offset, setOffset] = useState(0); | |
const [todos, setTodos] = useState([]); | |
const lastEl = useRef(); | |
useEffect(() => { | |
const fetchTodos = async () => { | |
const response = await fetch(`/todos?limit=${limit}&offset=${offset}`); | |
const json = await response.json(); | |
setTodos((prev) => [...prev, ...json]); | |
}; | |
fetchTodos(); | |
}, [limit, offset]); | |
useWhenVisible(lastEl.current, () => { | |
setOffset(offset + limit); | |
}); | |
return ( | |
<ul> | |
{todos.map((todo, index, arr) => ( | |
<li key={todo.id} ref={index === arr.length - 1 ? lastEl : undefined}> | |
{todo.title} - Completed: {todo.completed} | |
</li> | |
))} | |
</ul> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment