Add useFetch snippet

This commit is contained in:
Angelos Chalaris
2019-08-21 14:23:57 +03:00
parent da8096a895
commit bdd03cedfe
4 changed files with 147 additions and 0 deletions

View File

@ -58,6 +58,7 @@ import ReactDOM from 'react-dom';
* [`useClickInside`](#useclickinside) * [`useClickInside`](#useclickinside)
* [`useClickOutside`](#useclickoutside) * [`useClickOutside`](#useclickoutside)
* [`useFetch`](#usefetch)
* [`useInterval`](#useinterval) * [`useInterval`](#useinterval)
* [`useTimeout`](#usetimeout) * [`useTimeout`](#usetimeout)
@ -380,6 +381,61 @@ ReactDOM.render(
<br>[⬆ Back to top](#contents) <br>[⬆ Back to top](#contents)
### useFetch
A hook that implements `fetch` in a declarative manner.
- Create a custom hook that takes a `url` and `options`.
- Use the `React.useState()` hook to initialize the `response` and `error` state variables.
- Use the `React.useEffect()` hook to anychronously call `fetch()` and update the state varaibles accordingly.
- Return an object containting the `response` and `error` state variables.
```jsx
const useFetch = (url, options) => {
const [response, setResponse] = React.useState(null);
const [error, setError] = React.useState(null);
React.useEffect(() => {
const fetchData = async () => {
try {
const res = await fetch(url, options);
const json = await res.json();
setResponse(json);
} catch (error) {
setError(error);
}
};
fetchData();
}, []);
return { response, error };
};
```
<details>
<summary>Examples</summary>
```jsx
const ImageFetch = props => {
const res = useFetch('https://dog.ceo/api/breeds/image/random', {});
if (!res.response) {
return <div>Loading...</div>;
}
const dogName = res.response.status;
const imageUrl = res.response.message;
return (
<div>
<img src={imageUrl} alt="avatar" width={400} height="auto" />
</div>
);
};
ReactDOM.render(<ImageFetch />, document.getElementById('root'));
```
</details>
<br>[⬆ Back to top](#contents)
### useInterval ### useInterval
A hook that implements `setInterval` in a declarative manner. A hook that implements `setInterval` in a declarative manner.

View File

@ -463,6 +463,23 @@
"hash": "e8f3e64cd0cf616dd42843328234e37b1b7a77ed51da8956204fdb02e088ce33" "hash": "e8f3e64cd0cf616dd42843328234e37b1b7a77ed51da8956204fdb02e088ce33"
} }
}, },
{
"id": "useFetch",
"type": "snippetListing",
"title": "useFetch",
"attributes": {
"text": "A hook that implements `fetch` in a declarative manner.\n\n- Create a custom hook that takes a `url` and `options`.\n- Use the `React.useState()` hook to initialize the `response` and `error` state variables.\n- Use the `React.useEffect()` hook to anychronously call `fetch()` and update the state varaibles accordingly.\n- Return an object containting the `response` and `error` state variables.\n\n",
"tags": [
"hooks",
"effect",
"state",
"intermediate"
]
},
"meta": {
"hash": "848cb6ba4f8bd5dad012a38e6bd0e7c829a79b3215a23939c30a3f652627da4f"
}
},
{ {
"id": "useInterval", "id": "useInterval",
"type": "snippetListing", "type": "snippetListing",

View File

@ -631,6 +631,29 @@
"hash": "e8f3e64cd0cf616dd42843328234e37b1b7a77ed51da8956204fdb02e088ce33" "hash": "e8f3e64cd0cf616dd42843328234e37b1b7a77ed51da8956204fdb02e088ce33"
} }
}, },
{
"id": "useFetch",
"title": "useFetch",
"type": "snippet",
"attributes": {
"fileName": "useFetch.md",
"text": "A hook that implements `fetch` in a declarative manner.\n\n- Create a custom hook that takes a `url` and `options`.\n- Use the `React.useState()` hook to initialize the `response` and `error` state variables.\n- Use the `React.useEffect()` hook to anychronously call `fetch()` and update the state varaibles accordingly.\n- Return an object containting the `response` and `error` state variables.\n\n",
"codeBlocks": {
"style": "",
"code": "const useFetch = (url, options) => {\r\n const [response, setResponse] = React.useState(null);\r\n const [error, setError] = React.useState(null);\r\n\r\n React.useEffect(() => {\r\n const fetchData = async () => {\r\n try {\r\n const res = await fetch(url, options);\r\n const json = await res.json();\r\n setResponse(json);\r\n } catch (error) {\r\n setError(error);\r\n }\r\n };\r\n fetchData();\r\n }, []);\r\n\r\n return { response, error };\r\n};",
"example": "const ImageFetch = props => {\r\n const res = useFetch('https://dog.ceo/api/breeds/image/random', {});\r\n if (!res.response) {\r\n return <div>Loading...</div>;\r\n }\r\n const dogName = res.response.status;\r\n const imageUrl = res.response.message;\r\n return (\r\n <div>\r\n <img src={imageUrl} alt=\"avatar\" width={400} height=\"auto\" />\r\n </div>\r\n );\r\n};\r\n\r\nReactDOM.render(<ImageFetch />, document.getElementById('root'));"
},
"tags": [
"hooks",
"effect",
"state",
"intermediate"
]
},
"meta": {
"hash": "848cb6ba4f8bd5dad012a38e6bd0e7c829a79b3215a23939c30a3f652627da4f"
}
},
{ {
"id": "useInterval", "id": "useInterval",
"title": "useInterval", "title": "useInterval",

51
snippets/useFetch.md Normal file
View File

@ -0,0 +1,51 @@
---
title: useFetch
tags: hooks,effect,state,intermediate
---
A hook that implements `fetch` in a declarative manner.
- Create a custom hook that takes a `url` and `options`.
- Use the `React.useState()` hook to initialize the `response` and `error` state variables.
- Use the `React.useEffect()` hook to anychronously call `fetch()` and update the state varaibles accordingly.
- Return an object containting the `response` and `error` state variables.
```jsx
const useFetch = (url, options) => {
const [response, setResponse] = React.useState(null);
const [error, setError] = React.useState(null);
React.useEffect(() => {
const fetchData = async () => {
try {
const res = await fetch(url, options);
const json = await res.json();
setResponse(json);
} catch (error) {
setError(error);
}
};
fetchData();
}, []);
return { response, error };
};
```
```jsx
const ImageFetch = props => {
const res = useFetch('https://dog.ceo/api/breeds/image/random', {});
if (!res.response) {
return <div>Loading...</div>;
}
const dogName = res.response.status;
const imageUrl = res.response.message;
return (
<div>
<img src={imageUrl} alt="avatar" width={400} height="auto" />
</div>
);
};
ReactDOM.render(<ImageFetch />, document.getElementById('root'));
```