useToastContext

Typedefs

ToastState : Object
The current state of the toast store.
ToastContextProvider
A [context](https://reactjs.org/docs/context.html) provider that provides the toast state object and a dispatch function to toast functionality consumers.
useToastContextArray.<Object>
A hook that provides access to the toast state and dispatch. Any component using this hook _must_ be a child of a [ToastContextProvider](#ToastContextProvider).

The current state of the toast store.

Properties

Name Type Description
toasts Map Map object associating an id to toast data

A context provider that provides the toast state object and a dispatch function to toast functionality consumers.

A hook that provides access to the toast state and dispatch. Any component using this hook must be a child of a ToastContextProvider.

**Returns: ** Array.<Object> — An array containing the state and dispatch function: [ToastState, function]

Example

const [toastState, dispatch] = useToastState();

Source Code: pwa-studio/packages/peregrine/lib/Toasts/useToastContext.js

Examples

Using the Toast context logic

Import the ToastContextProvider and wrap it around components that use Toast data and functionality.

// MyComponent.js

import {ToastContextProvider} from '@magento/peregrine'
import {ToastContainer, AddToastComponent} from './MyToastComponents'

...

const MyComponent = () =>{

  return (
  <ToastContextProvider>
    <ToastContainer /> // A component which would display based on state.
    <AddToastComponent /> // A component which adds a toast using actions.
  </ToastContextProvider>
  )
}

...

Call useToastContext() to get the current state of the toast store and a dispatch function.

// MyToastComponents.js

import {useToastContext} from '@magnto/peregrine';

export const ToastContainer = () =>{
  const [toastState, toastDispatch] = useToastContext();

  const toastData = toastState.map(toast=>{
    // Do something with the toast data
  })

  return <div>{toastData}</div>
}

export const AddToastComponent = () =>{
  return
  (
    <div>
    // Some component that allows you to add toast data using the
    // toastDispatch() function or useToast() hook
    </div>
  )
}