Created
July 22, 2022 02:00
-
-
Save jayeshcp/81eff8d29e7554acfbcea732bbacefa8 to your computer and use it in GitHub Desktop.
React Snippets
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'; | |
/* Custom hook */ | |
function useAPIFetch(apiURL) { | |
const [loading, setLoading] = useState(true); | |
const [data, setData] = useState(null); | |
function fetchData() { | |
setLoading(true); | |
fetch(apiURL) | |
.then((response) => response.json()) | |
.then((responseData) => { | |
setData(responseData); | |
setLoading(false); | |
}); | |
} | |
useEffect(() => { | |
fetchData(); | |
}, []); | |
return [data, fetchData, loading]; | |
} | |
/* Use above custom hook as shown below */ | |
function Block() { | |
const [data, fetchData, loading] = useAPIFetch('https://jsonplaceholder.typicode.com/todos'); | |
return ( | |
<> | |
<button onClick={fetchData}>Refresh</button | |
<div className="block"> | |
{loading && <div>Loading ...</div>} | |
{!loading && <div>{JSON.stringify(data)}</div>} | |
</div> | |
</> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment