usePromise()

The usePromise() hook simplifies handling asynchronous operations by managing the state of a Promise-based function.

Functionality Overview:

The usePromise() hook simplifies asynchronous operations in functional components.

It manages three states: result, error, and loading with a refresh function.

Execute the async tasks with refresh() and handle the result, error, and loading states accordingly.

Here's an example:

import { usePromise } from '@magicjs.dev/frontend';
import fetchDataServer from './fetch-data.server';

const MyComponent = () => {
    const { refresh, result, error, loading } = usePromise(fetchData);

    // Execute fetchData when component mounts or whenever needed
    useEffect(() => {
        refresh();
    }, []);

    return (
        <div>
            {
                loading && <p>Loading...</p>
            }
            {
                error && <p>Error: {error.message}</p>
            }
            {
                result && <p>Data: {result}</p>
            }
        </div>
    );
}

Click here to refer GitHub.

Last updated