Created
August 4, 2020 10:08
-
-
Save hyber1z0r/34cf0291a342771dd6639a9b2fa0f99d to your computer and use it in GitHub Desktop.
useInterval 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, { 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