Skip to content

Instantly share code, notes, and snippets.

@hyber1z0r
Created August 4, 2020 10:08
Show Gist options
  • Save hyber1z0r/34cf0291a342771dd6639a9b2fa0f99d to your computer and use it in GitHub Desktop.
Save hyber1z0r/34cf0291a342771dd6639a9b2fa0f99d to your computer and use it in GitHub Desktop.
useInterval example
import React, { useState, useCallback } from 'react';
import useInterval from './useInterval';
const ShoppingList = () => {
// Wait 5 seconds before fetching new data
const POLL_DELAY = 5000;
const [items, setItems] = useState([]);
const fetchItems = useCallback(async () => {
const response = await fetch('/shopping-list/items');
const json = await response.json();
setItems(json);
}, []);
useEffect(() => {
// Fetch items from API on mount
fetchItems();
}, []);
useInterval(() => {
fetchItems();
}, POLL_DELAY);
return (
<ul>
{items.map((item) => <li>{item.title}</li>)}
</ul>
)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment