Skip to content

Instantly share code, notes, and snippets.

@hyber1z0r
Created August 4, 2020 09:58
Show Gist options
  • Save hyber1z0r/33572e706631a1b2d767c62d20059780 to your computer and use it in GitHub Desktop.
Save hyber1z0r/33572e706631a1b2d767c62d20059780 to your computer and use it in GitHub Desktop.
useWhenVisible example
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