> ## Documentation Index
> Fetch the complete documentation index at: https://veekthoven-laravel-inertia-toast-24-61.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# useToast

> React hook for programmatically triggering toast notifications

The `useToast` hook provides access to the toast context, allowing you to display notifications from anywhere in your React application.

## Usage

```tsx theme={null}
import { useToast } from 'laravel-inertia-toast/react'

function MyComponent() {
  const toast = useToast()
  
  const handleSuccess = () => {
    toast.success('Operation completed successfully!')
  }
  
  return (
    <button onClick={handleSuccess}>
      Click me
    </button>
  )
}
```

<Note>
  The `useToast` hook must be used within a component that is a child of `ToastProvider`. It will throw an error if used outside the provider context.
</Note>

## Return value

The hook returns a `ToastContextValue` object with the following properties and methods:

### Properties

<ResponseField name="items" type="ToastItem[]">
  Array of currently active toast items. Each item contains:

  ```typescript theme={null}
  interface ToastItem {
    id: string              // Auto-generated unique identifier
    message: string         // Toast message content
    level: ToastLevel       // 'success' | 'error' | 'info' | 'warning'
    title: string | null    // Optional title
    duration: number | null // Optional duration override
  }
  ```
</ResponseField>

<ResponseField name="config" type="ToastConfig">
  The current toast configuration:

  ```typescript theme={null}
  interface ToastConfig {
    duration: number     // Default: 5000ms
    position: string     // Default: 'top-right'
    maxVisible: number   // Default: 5
    propKey: string      // Default: 'toasts'
  }
  ```
</ResponseField>

### Methods

<ResponseField name="success" type="(message: string, options?: ToastOptions) => void">
  Display a success toast notification.

  **Parameters:**

  * `message` (string): The message to display
  * `options` (ToastOptions, optional):
    * `title` (string, optional): Optional title above the message
    * `duration` (number, optional): Custom duration in milliseconds

  **Example:**

  ```tsx theme={null}
  toast.success('User created successfully')
  toast.success('Profile updated', { title: 'Success' })
  toast.success('Changes saved', { duration: 3000 })
  ```
</ResponseField>

<ResponseField name="error" type="(message: string, options?: ToastOptions) => void">
  Display an error toast notification.

  **Parameters:**

  * `message` (string): The error message to display
  * `options` (ToastOptions, optional):
    * `title` (string, optional): Optional title above the message
    * `duration` (number, optional): Custom duration in milliseconds

  **Example:**

  ```tsx theme={null}
  toast.error('Failed to save changes')
  toast.error('Invalid credentials', { title: 'Authentication Error' })
  toast.error('Network error', { duration: 0 }) // No auto-dismiss
  ```
</ResponseField>

<ResponseField name="info" type="(message: string, options?: ToastOptions) => void">
  Display an informational toast notification.

  **Parameters:**

  * `message` (string): The informational message to display
  * `options` (ToastOptions, optional):
    * `title` (string, optional): Optional title above the message
    * `duration` (number, optional): Custom duration in milliseconds

  **Example:**

  ```tsx theme={null}
  toast.info('Your session will expire in 5 minutes')
  toast.info('New features available', { title: 'Update' })
  ```
</ResponseField>

<ResponseField name="warning" type="(message: string, options?: ToastOptions) => void">
  Display a warning toast notification.

  **Parameters:**

  * `message` (string): The warning message to display
  * `options` (ToastOptions, optional):
    * `title` (string, optional): Optional title above the message
    * `duration` (number, optional): Custom duration in milliseconds

  **Example:**

  ```tsx theme={null}
  toast.warning('Unsaved changes will be lost')
  toast.warning('Low disk space', { title: 'Warning' })
  ```
</ResponseField>

<ResponseField name="remove" type="(id: string) => void">
  Remove a specific toast by its ID.

  **Parameters:**

  * `id` (string): The unique identifier of the toast to remove

  **Example:**

  ```tsx theme={null}
  // Remove a specific toast
  const toastId = toast.items[0]?.id
  if (toastId) {
    toast.remove(toastId)
  }
  ```

  <Note>
    You rarely need to use this method directly, as toasts auto-dismiss and have close buttons.
  </Note>
</ResponseField>

<ResponseField name="clear" type="() => void">
  Remove all active toasts immediately.

  **Example:**

  ```tsx theme={null}
  // Clear all toasts when navigating away
  const handleNavigation = () => {
    toast.clear()
    router.visit('/dashboard')
  }
  ```
</ResponseField>

## TypeScript types

```typescript theme={null}
type ToastLevel = 'success' | 'error' | 'info' | 'warning'

interface ToastOptions {
  title?: string
  duration?: number
}

interface ToastMessage {
  message: string
  level: ToastLevel
  title: string | null
  duration: number | null
}

interface ToastItem extends ToastMessage {
  id: string
}

interface ToastConfig {
  duration: number
  position: string
  maxVisible: number
  propKey: string
}

interface ToastContextValue {
  items: ToastItem[]
  config: ToastConfig
  success: (message: string, options?: ToastOptions) => void
  error: (message: string, options?: ToastOptions) => void
  info: (message: string, options?: ToastOptions) => void
  warning: (message: string, options?: ToastOptions) => void
  remove: (id: string) => void
  clear: () => void
}
```

## Examples

### Basic toast notifications

```tsx theme={null}
import { useToast } from 'laravel-inertia-toast/react'

function UserForm() {
  const toast = useToast()
  
  const handleSubmit = async (data) => {
    try {
      await saveUser(data)
      toast.success('User saved successfully')
    } catch (error) {
      toast.error('Failed to save user')
    }
  }
  
  return <form onSubmit={handleSubmit}>...</form>
}
```

### Toast with title

```tsx theme={null}
import { useToast } from 'laravel-inertia-toast/react'

function Dashboard() {
  const toast = useToast()
  
  const showWelcome = () => {
    toast.success('Your account is now active', {
      title: 'Welcome aboard!'
    })
  }
  
  return <button onClick={showWelcome}>Show Welcome</button>
}
```

### Custom duration

```tsx theme={null}
import { useToast } from 'laravel-inertia-toast/react'

function ImportantAlert() {
  const toast = useToast()
  
  const showCriticalError = () => {
    // Error stays visible until manually dismissed
    toast.error('Critical system error occurred', {
      title: 'Error',
      duration: 0
    })
  }
  
  const showQuickNotice = () => {
    // Disappears after 2 seconds
    toast.info('Processing started', {
      duration: 2000
    })
  }
  
  return (
    <>
      <button onClick={showCriticalError}>Critical Error</button>
      <button onClick={showQuickNotice}>Quick Notice</button>
    </>
  )
}
```

### Form validation

```tsx theme={null}
import { useToast } from 'laravel-inertia-toast/react'
import { useForm } from '@inertiajs/react'

function LoginForm() {
  const toast = useToast()
  const { data, setData, post, processing } = useForm({
    email: '',
    password: ''
  })
  
  const handleSubmit = (e) => {
    e.preventDefault()
    
    post('/login', {
      onSuccess: () => {
        toast.success('Login successful')
      },
      onError: (errors) => {
        if (errors.email) {
          toast.error(errors.email, { title: 'Validation Error' })
        }
      }
    })
  }
  
  return <form onSubmit={handleSubmit}>...</form>
}
```

### Clearing toasts on navigation

```tsx theme={null}
import { useToast } from 'laravel-inertia-toast/react'
import { router } from '@inertiajs/react'
import { useEffect } from 'react'

function MyComponent() {
  const toast = useToast()
  
  useEffect(() => {
    // Clear all toasts when component unmounts
    return () => toast.clear()
  }, [])
  
  const navigateAway = () => {
    toast.clear()
    router.visit('/dashboard')
  }
  
  return <button onClick={navigateAway}>Go to Dashboard</button>
}
```

### Accessing current toasts

```tsx theme={null}
import { useToast } from 'laravel-inertia-toast/react'

function ToastDebugger() {
  const { items, config } = useToast()
  
  return (
    <div>
      <h3>Active Toasts: {items.length}</h3>
      <p>Position: {config.position}</p>
      <p>Max Visible: {config.maxVisible}</p>
      <ul>
        {items.map(item => (
          <li key={item.id}>
            [{item.level}] {item.message}
          </li>
        ))}
      </ul>
    </div>
  )
}
```

## Error handling

The hook throws an error if used outside of `ToastProvider`:

```tsx theme={null}
import { useToast } from 'laravel-inertia-toast/react'

// This will throw an error
function ComponentOutsideProvider() {
  const toast = useToast() // Error: useToast must be used within a <ToastProvider>
  // ...
}
```

Always ensure your components are wrapped with `ToastProvider`:

```tsx theme={null}
import { ToastProvider } from 'laravel-inertia-toast/react'

function App() {
  return (
    <ToastProvider>
      <ComponentUsingToast /> {/* Now this works! */}
    </ToastProvider>
  )
}
```
