Skip to content

A short react helper snippet to handle promises synchronously through a very simple hook

License

Notifications You must be signed in to change notification settings

filipomar/react-sync-promise

Folders and files

NameName
Last commit message
Last commit date

Latest commit

32f16a4 · Aug 1, 2022

History

11 Commits
Jun 29, 2022
Aug 1, 2022
Jul 3, 2022
Dec 3, 2020
Jul 3, 2022
Dec 3, 2020
Jun 29, 2022
Dec 3, 2020
Jul 2, 2022
Dec 3, 2020
Jul 3, 2022
Jun 29, 2022
Jun 29, 2022
Aug 1, 2022
Aug 1, 2022
Jun 29, 2022

Repository files navigation

react-sync-promise

A simple react helper snippet to handle promises as a react synchronous hook with mininmal amount of re-renders

Usage

import React, { FC, useMemo } from 'react';
import { usePromise, isPending, isRejected, isResolved, ifUnresolved, ifNotRejected, usePromiseState } from 'react-sync-promise';

export const PrequelsSurprise: FC = () => {
    const memoizedPromise = useMemo(() => Promise.resolve('Execute order 66'), []);

    const syncPromise = usePromise(memoizedPromise);
    const [secondSyncPromise, setSecondSyncPromise] = usePromiseState(memoizedPromise);

    return (
        <>
            <p>
                {`JSON: ${JSON.stringify(secondSyncPromise)}`}
                <button type="button" aria-label="Update Promise" onClick={() => setSecondSyncPromise(Promise.resolve('This is where the fun begins'))} />
            </p>
            <p>{`JSON: ${JSON.stringify(syncPromise)}`}</p>
            <p>{`isPending: ${String(isPending(syncPromise))}`}</p>
            <p>{`isRejected: ${String(isRejected(syncPromise))}`}</p>
            <p>{`isResolved: ${String(isResolved(syncPromise))}`}</p>
            <p>{`ifUnresolved: ${String(ifUnresolved(syncPromise, 'Hello There'))}`}</p>
            <p>{`ifNotRejected: ${String(ifNotRejected(syncPromise, 'General kenobi'))}`}</p>
        </>
    );
};

License

APACHE

About

A short react helper snippet to handle promises synchronously through a very simple hook

Resources

License

Stars

Watchers

Forks

Packages

No packages published