Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jayeshcp/81eff8d29e7554acfbcea732bbacefa8 to your computer and use it in GitHub Desktop.
Save jayeshcp/81eff8d29e7554acfbcea732bbacefa8 to your computer and use it in GitHub Desktop.
React Snippets
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