Last active
November 12, 2020 19:31
-
-
Save crshmk/d694dee7d70d9fc53bee1da42232da8c to your computer and use it in GitHub Desktop.
fetching with hooks
This file contains hidden or 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8" /> | |
<title>Sandbox</title> | |
<script src="https://unpkg.com/react@16/umd/react.development.js"></script> | |
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> | |
<script src="https://unpkg.com/[email protected]/babel.min.js"></script> | |
</head> | |
<body> | |
<div id="app"></div> | |
<script type="text/babel"> | |
let { useEffect, useState } = React | |
function useName(id) { | |
let [name, setName] = useState('fetching') | |
useEffect(() => { | |
fetch(`https://jsonplaceholder.typicode.com/users/${id}`) | |
.then(res => res.json()) | |
.then(user => setName(user.name)) | |
.catch(console.log) | |
}, [id]) | |
return name | |
} | |
function User1(props) { | |
let name = useName(1) | |
return <p>user 1 is {name}</p> | |
} | |
function User2() { | |
let name = useName(2) | |
return <p>user 2 is {name}</p> | |
} | |
function App() { | |
return ( | |
<div> | |
<User1 /> | |
<User2 /> | |
</div> | |
) | |
} | |
ReactDOM.render( | |
<App />, | |
document.getElementById('app') | |
) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment