Toast

Use toast to create a toast from anywhere in your React application.

πŸ’‘ Make sure you add the <Toaster /> provider to your app first.

  1. Import the toast function:
import { toast } from '@pheralb/toast';
  1. Render a toast:
toast.default({
  text: `A toast with πŸ‘€ action button`,
  action: {
    label: 'Action', // Button label
    onClick: () => {
      // Do something
    },
  },
});
toast.loading({
  // Initial message:
  text: 'Loading',
  options: {
    promise: yourFunction(),
    success: 'Ready',
    error: 'Error',
    // Close toast automatically (the duration depends by delayDuration property):
    autoDismiss: true,
    // Optional:
    onSuccess: () => {
      console.log('Success');
    },
    // Optional:
    onError: () => {
      console.log('Error');
    },
  },
});

✨ For example, you can use Next.js Server Actions to show a loading toast while fetching data from an API:

// πŸ“ƒ actions/testAction.ts
'use server';

export const testAction = async (name: string) => {
  await new Promise((resolve) => setTimeout(resolve, 1000));
  return {
    name: `Hello, ${name}!`,
  };
};

// πŸ“ƒ components/Example.tsx

import { testAction } from '@/actions/testAction';
import { toast } from '@pheralb/toast';

toast.loading({
  text: 'Getting data',
  options: {
    promise: testAction(),
    success: 'Ready',
    error: 'Error',
    autoDismiss: false,
    onSuccess: (data) => {
      console.log(`Success: ${data.name}`);
      // Success: Hello, pheralb!
    },
  },
});

API Reference

The toast.variant function accepts the following options:

PropertyDescriptionTypeRequired
textNotification titlestringβœ…
descriptionToast’s descriptionstring-
iconIcon to display in the toastReactNode-
delayDurationDuration before the toast disappearsnumber (default: 4000)-
themeTheme of the toastTheme (default: system): light, dark or system-
actionShow a Action button and execute a functionlabel (default text: action) & onClick: () => void or Promise<void>-