fetch
API can be used to fetch data from databases or other locations on the internetcomponentDidMount
lifecycle processuseState
and useEffect
hooks respectivelyTo fetch data (and store it) in a functional component we need to use Hooks
setState
useEffect
Note: Changing state triggers a re-render, a re-render triggers
useEffect
so remember to wrap your state changes in conditionals, or you'll be trapped in an infinte render cycle.
function DisplayMessages(props) {
}
Let's practice fetching data with useEffect
by creating a React app that fetches a list of users, and displays them on the page
https://jsonplaceholder.typicode.com/users
fetch
using APIs happenfunction AuthorList(props) {
const [authors, setAuthors] = useState(null)
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then(res => {
setAuthors(res)
}).catch((err) => {
alert('Something went wrong...')
console.error(err.message)
})
})
return(
<ul>
{authors ? authors.map((author) => {
return <li>{author.name}</li>
}) : 'loading...'}
</ul>
)
}
https://codesandbox.io/embed/p99mqrq9z0
See the Pen Fetching API Data by Joshua Burke (@Dangeranger) on CodePen.
/