Created
March 6, 2020 11:40
-
-
Save markodayan/1d57878c0da6384a56bc750a896899db to your computer and use it in GitHub Desktop.
Custom HTTP request using custom React hook
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 { 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