Skip to content

Instantly share code, notes, and snippets.

@markodayan
Created March 6, 2020 11:40
Show Gist options
  • Save markodayan/1d57878c0da6384a56bc750a896899db to your computer and use it in GitHub Desktop.
Save markodayan/1d57878c0da6384a56bc750a896899db to your computer and use it in GitHub Desktop.
Custom HTTP request using custom React hook
import { useEffect, useState } from 'react';
export const useFetch = url => {
const [info, setInfo] = useState({ data: null, loading: true });
useEffect(() => {
setInfo({ data: null, loading: true });
fetch(url)
.then(x => x.text())
.then(y => {
setInfo({ data: y, loading: false});
});
}, [url]);
}
// OR
export const useFetch = url => {
const [info, setInfo] = useState({ data: null, loading: true });
useEffect(() => {
setInfo(info => { data: info.data, loading: true });
fetch(url)
.then(x => x.text())
.then(y => {
setInfo({ data: y, loading: false});
});
}, [url, setInfo]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment