# usePromise()

### 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:

```typescript
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.](https://github.com/skyslit/magicjs.dev/blob/main/packages/frontend/src/use-promise.tsx)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://skyslit.gitbook.io/magicjs/api-references/frontend/usepromise.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
