Created
October 19, 2019 18:10
-
-
Save dileno/13311748c6843d5788d6b54b7604863e to your computer and use it in GitHub Desktop.
RandomUser.js React Hooks sample
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, useEffect } from 'react'; | |
export default function RandomUser() { | |
const [user, setUser] = useState([]); | |
const [error, setError] = useState([]); | |
const [isLoading, setIsLoading] = useState(true); | |
async function fetchRandomUser() { | |
try { | |
await fetch('https://randomuser.me/api/') | |
.then(results => { | |
return results.json(); | |
}) | |
.then(data => { | |
let user = data.results.map((user) => { | |
let userElm = ''; | |
if (typeof user !== undefined && typeof user.name !== undefined && typeof user.picture !== undefined) { | |
userElm = <div key={user}> | |
<h2>{user.name.first} {user.name.last}</h2> | |
<img src={user.picture.large} alt="" /> | |
</div>; | |
} | |
return userElm; | |
}); | |
setUser(user); | |
setIsLoading(false); | |
}); | |
} | |
catch(error) { | |
setError(error); | |
setIsLoading(false); | |
} | |
} | |
useEffect(() => { | |
fetchRandomUser(); | |
}, []); | |
return( | |
<div> | |
{error && <p>{error.message}</p>} | |
{isLoading && <p>Loading...</p>} | |
{user} | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment