Promise
toast.promise receives the status of the promis and displays the loading before resolve, reject, and updates the data of the toast when the promise is fulfilled.
Usage
import { toast } from 'react-strawberry-toast';
function ShowPromiseButton() {
const onClick = () => {
const promise = new Promise<number>((resolve) => {
setTimeout(() => resolve(123), 3_000);
});
toast.promise(promise, {
loading: 'loading',
success: (res) => <div>resolved value: {res}</div>,
error: 'error',
});
};
return (
<button type="button" onClick={onClick}>
show promise
</button>
);
}
Props
option | description | type |
---|---|---|
promise | promise variable | Promise |
options.loading | Data to show when promise is pending | ReactNode |
options.success | Data to show when promise is resolve | ReactNode |
options.error | Data to show when promise is reject | ReactNode |
Headless
You can handle promise with the headless hook.
import { toast } from 'react-strawberry-toast/dist/headless';
function ShowPromiseButton() {
const onClick = () => {
const toastId = toast('loading');
const promise = new Promise<number>((resolve) => {
setTimeout(() => resolve(123), 3_000);
});
promise.then((res) => {
toast.replace(toastId, <div>{res}</div>);
}).catch(() => {
toast.replace(toastId, 'error');
});
};
return (
<button type="button" onClick={onClick}>
show promise
</button>
);
}