@josipp/use-fetch

2.1.0 • Public • Published

@josipp/use-fetch

A custom React hook to execute multiple api requests sequentially.

Install

npm i @josipp/use-fetch

Usage

import { useEffect, useState } from 'react';
import useFetch from '@josipp/use-fetch';

const baseUrl = 'https://jsonplaceholder.typicode.com';

function App() {
    const [users, setUsers] = useState(null);
    const {
        doFetch,
        isLoading,
        response,
        error: { error, msg },
    } = useFetch();

    useEffect(() => {
        doFetch([
            // id is key in response object, it is optional
            // options are also optional
            { url: `${baseUrl}/posts`, id: 'posts' },
            { url: `${baseUrl}/users`, options: { method: 'GET' } },
            // you can also set to another state manager, like redux or do something else
            // with data
            { func: data => setUsers(data) },
            {
                url: `${baseUrl}/posts`,
                options: {
                    method: 'POST',
                    body: JSON.stringify({ title: 'test', body: 'test', userId: 2 }),
                    headers: {
                        'Content-type': 'application/json; charset=UTF-8',
                    },
                },
            },
        ]);
    }, [doFetch]);

    if (isLoading) {
        // can be used for loading indicator
        return <h1>Loading...</h1>;
    }

    if (error) {
        console.log(msg);
        return <h1>Something went wrong.</h1>;
    }

    return (
        <>
            <p>{JSON.stringify(response.posts)}</p>
            <br />
            <p>{JSON.stringify(response[1])}</p>
            <br />
            <p>{JSON.stringify(users)}</p>
            <br />
            <p>{JSON.stringify(response[3])}</p>
        </>
    );
}

export default App;

Versions

Current Tags

VersionDownloads (Last 7 Days)Tag
2.1.01latest

Version History

VersionDownloads (Last 7 Days)Published
2.1.01
2.0.251
2.0.241
2.0.231
2.0.221
2.0.210
2.0.200
2.0.190
2.0.180
2.0.170
2.0.160
2.0.150
2.0.140
2.0.130
2.0.120
2.0.110
2.0.100
2.0.90
2.0.80
2.0.70
2.0.60
2.0.50
2.0.40
2.0.30
2.0.20
2.0.10
2.0.00
1.0.00

Package Sidebar

Install

npm i @josipp/use-fetch

Weekly Downloads

5

Version

2.1.0

License

ISC

Unpacked Size

41.6 kB

Total Files

22

Last publish

Collaborators

  • josipp