use-fetched-state
TypeScript icon, indicating that this package has built-in type declarations

2.37.0 • Public • Published

use-fetched-state

npm package

A simple yet convenient `fetch` + `useState` wrapper. 100% TS. Less than 200 LOC. 0 dependencies.

Please submit PRs / create issues if (simple) functionality missing.

Example

import React, { FC } from "react";
import { createUseFetchedState } from "use-fetched-state";

interface IUser {
    name: string;
    id: number;
}

const getDefaultUser = (): IUser => ({ name: "", id: -1 });

const useFetchedUser = createUseFetchedState<{ user?: IUser }, IUser, number>(
    (id) => `/api/v1/user/${id}` /** can also be just a string */,
    (data) => data.user ?? getDefaultUser()
);

const User: FC = () => {
    const [user, setUser, isLoading] = useFetchedUser(
        () => getDefaultUser() /** (get) initial state */,
        [] /** dependencies to trigger re-fetch */,
        {
            /** option(s) for the URL creator: */
            urlCtx: 1,
            /** options: */
            fetchOpts: {} /** AbortController setup & enabled by default */,
            shouldFetch: (ctx) => true /** true by default, but controllable here */,
            onError: (e, ctx) => console.error(e),
            onSuccess: (u, ctx) => console.info(`fetched user ${u.name}`),
            onSetState: async (ctx) => {} /** potentially up-sync the new state to the API */
        }
    );

    if (isLoading) return null;

    return <h1>hello, {user.name}</h1>;
};

License

MIT

Versions

Current Tags

VersionDownloads (Last 7 Days)Tag
2.37.071latest

Version History

VersionDownloads (Last 7 Days)Published
2.37.071
2.35.11
2.35.00
2.34.10
2.34.00
2.33.00
2.32.10
2.31.10
2.31.00
2.30.30
2.30.20
2.30.10
2.30.00
2.29.00
2.28.31
2.28.20
2.28.10
2.28.00

Package Sidebar

Install

npm i use-fetched-state

Weekly Downloads

8

Version

2.37.0

License

MIT

Unpacked Size

28.6 kB

Total Files

20

Last publish

Collaborators

  • kipras