Skip to content

Instantly share code, notes, and snippets.

@hardikmodi1
Created March 23, 2019 11:48
Show Gist options
  • Select an option

  • Save hardikmodi1/b16c9e42b6232329ebf69586113e5857 to your computer and use it in GitHub Desktop.

Select an option

Save hardikmodi1/b16c9e42b6232329ebf69586113e5857 to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'react';
export const useApi = (url, dependencies) => {
const [isLoading, setIsLoading] = useState(false);
const [data, setData] = useState(null);
useEffect(() => {
setIsLoading(true);
console.log('Sending Http request to URL: ' + url);
fetch(url)
.then(response => {
if (!response.ok) {
console.log("Error in fetching data");
}
return response.json();
})
.then(data => {
setIsLoading(false);
setData(data);
})
.catch(err => {
console.log(err);
setIsLoading(false);
});
}, dependencies);
return [isLoading, data];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment