useFetch - React custom hook
Hook to fetch data with fetchAPI.
Also can handle errors and loading state.
Why useFetch?
With this hook, you can get a json data from an url and handle the following variables:
- Fetched data.
- Loading boolean.
- Error data.
When that vars are updated, your component is re-rendedred.
Usage
Just install:
npm install react-hook-usefetch
And import the hook.
;
Use it in your component:
const YourComponent = { ... const data = ; ...}
Optional, you can send personal settings as second parameter:
const headers = ; const options = method: 'GET' headers mode: 'cors' cache: 'default' ...more;
Full Example
;; { const data loading error = ; const getData = { if errorstatus return <li><p>Error: errormessage</p></li>; if loading return <li><p>Loading...</p></li>; if dataresults return dataresults; } return <div> <h1>Test</h1> <ul> </ul> </div> ; }