Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 30, 2021 09:22 pm GMT

Easily fetch data: react-api-hook

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


Original Link: https://dev.to/demicdev/easily-fetch-data-react-api-hook-2npn

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To