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!
Top comments (4)
Add a few more requests and turn your components into an unreadable mess.
What do you mean?
Can you run multiple requests in parallel? Can you chain one request to another?
If you have to run multiple request, you only have to declare another hook: