Categories:

Fetching API using React useState and useEffect

ENV: React 16.9, Nodejs 12
IDE: Visual Studio Code
OS: Mac OSX

// RandomPerson.js

export const RandomPerson = () => {
 const [person, setPerson] = useState()
 useEffect(() => {
   fetch("https://randomuser.me/api")
     .then(x => x.json())
     .then(x => setPerson(x))
 }, []) // Run only on render

 return (
   <div>
    <pre>
      {JSON.stringify(person, null, 2)}
    </pre>
   </div>
 )
}

Photo by ROOM on Unsplash