Created
June 17, 2019 06:38
-
-
Save imparvez/0b4f0ee282cc705c7efb8caed0aa2db6 to your computer and use it in GitHub Desktop.
Fetch data using useEffect hooks in React
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
import React, { useState, useEffect } from 'react'; | |
const useFetch = (url) => { | |
const [data, setData] = useState(null) | |
const [loading, setLoading] = useState(true) | |
useEffect( async () => { | |
const response = await fetch(url) | |
const data = await response.json() | |
const [ item ] = data.results | |
setData(item) | |
setLoading(false) | |
}, []) | |
return { data, loading } | |
} | |
function App() { | |
const [count, setCount] = useState(0) | |
const {data, loading} = useFetch('https://api.randomuser.me/') | |
return ( | |
<div className="App"> | |
<p>{`You clicked ${count} times`}</p> | |
<button onClick={() => setCount(count + 1)}>Increase Count</button> | |
{loading ? <div>...Loading</div> : <p>{data.name.first}</p>} | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment