Perform Asynchronous Actions (like fetching http data) in React with useEffect

InstructorChris Achard

Share this video with your friends

Send Tweet

🚨 The correct url is now "https://swapi.dev/api/people/"

Whenever doing a side effect (like fetching data) in React, we can use the useEffect hook to perform that action and then set state afterwards.

So we'll fetch some data inside of useEffect like this:

  useEffect(() => {
    console.log(props.id)
    fetch("https://swapi.co/api/people/"+props.id)
      .then(response => response.json())
      .then(result => setData(result))
  }, [props.id])

Caution! make sure to set the dependency array (the second argument to useEffect) to contain any data that you use inside of the useEffect. Otherwise you could end up with an infinite loop as the useEffect will run every time the component in re-rendered.

Christian Grefer
~ 3 years ago

β€ž[…] Then down in our render method […]β€œ. As this is not a class components there is actually no method to speak of. I hope this does not lead to any confusion.

~ 3 years ago

Url changed to "https;//www.swapi.tech/api/people/" Then in GetData paragraph component must return data.result.properties.name to display the name