This content originally appeared on DEV Community and was authored by Michele
When developing a complex web app with React, the best thing is modularise and break up the code in smaller components, hooks or functions.
So our code will be easier to maintain during the time, and it is more readable.
While reading this blog post, I understood how the usually fetch handling with:
import React, { useState } from 'react'
const ComponentWithFetch = () => {
const [data, setData] = useState();
const [isLoading, setIsLoading] = useState();
const fetchTheData = () => {
setIsLoading(true);
//handle the fetch
};
return (
<button
onClick={fetchTheData}
disabled={isLoading}
>
Start
</button>
);
};
export default ComponentWithFetch;
Is basically wrong, because is detached from the logic, and this is not good.
So, I decided to make a package, to make this easier, and simply integrate in a project, declaring the hook in the component and passing the datas as parameters.
All the states of the fetch will be executed separately, in an independent logic, handled by useReducer.
It is also possible to cancel the request and the state will update with inAbort
and then canceled
To install the package:
Go to the root of your React Project and, on the terminal, write:
npm i react-api-hook
How to use the package
Now, you can use the package in any component:
import React, { useEffect } from "react";
import useAPIHook from "react-api-hook";
function App() {
const [state, send, cancel] = useAPIHook(
"https://jsonplaceholder.typicode.com/posts",
{ method: "GET" },
);
useEffect(() => {
if (status.status === "success") {
console.log(status.data);
//status.data.json() for the body of response
}
if(status.status === "failure") {
console.log(status.error);
}
}, [status]);
return (
<div className="App">
<header className="App-header">
<div>{status.state}</div>
<div>
<button onClick={send}>start fetching</button>
<button onClick={cancel}>stop fetching</button>
</div>
</header>
</div>
);
}
export default App;
You will see in the console the response and, on the screen, the status of the request.
Thanks for reading! I'm open to any pull request or suggestions in the comment!
Package link
This content originally appeared on DEV Community and was authored by Michele
Michele | Sciencx (2021-04-30T21:22:02+00:00) Easily fetch data: react-api-hook. Retrieved from https://www.scien.cx/2021/04/30/easily-fetch-data-react-api-hook/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.