2.35.1 • Published 10 days ago

use-fetched-state v2.35.1

Weekly downloads
-
License
MIT
Repository
github
Last release
10 days ago

use-fetched-state

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

2.35.1

10 days ago

2.35.0

11 days ago

2.34.1

14 days ago

2.34.0

14 days ago

2.33.0

9 months ago

2.32.1

2 years ago

2.31.1

2 years ago

2.31.0

2 years ago

2.30.3

3 years ago

2.30.2

3 years ago

2.30.1

3 years ago

2.30.0

3 years ago

2.29.0

3 years ago

2.28.1

3 years ago

2.28.3

3 years ago

2.28.2

3 years ago

2.28.0

3 years ago