Fetching Data

Fetching Data Cont.

Fetching Data With Hooks

To fetch data (and store it) in a functional component we need to use Hooks

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.

Fetching Data Example


function DisplayMessages(props) {

}

Lab: Functional Fetching

Let's practice fetching data with useEffect by creating a React app that fetches a list of users, and displays them on the page

Fetching Data - Handle Errors

Component with Error Handling

function 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>
  )
}

Fetching Data - Example

https://codesandbox.io/embed/p99mqrq9z0

See the Pen Fetching API Data by Joshua Burke (@Dangeranger) on CodePen.

 Previous Next 

Outline

[menu]

/