React.useRef for ChakraUI Toast

Viewed 1433

I can't work out what Type I need to provide for for React.useRef() given the following example code from the chakra docs:

function UpdatingToastExample() {
  const toast = useToast()
  const toastIdRef = React.useRef()

  function update() {
    if (toastIdRef.current) {
      toast.update(toastIdRef.current, { description: "new text" })
    }
  }

  function addToast() {
    toastIdRef.current = toast({ description: "some text" })
  }

  return (
    <Stack isInline spacing={2}>
      <Button onClick={addToast} type="button">
        Toast
      </Button>

      <Button onClick={update} type="button" variant="outline">
        Update last toast
      </Button>
    </Stack>
  )
}

From: https://chakra-ui.com/docs/feedback/toast#updating-toasts

Typescript obviously wants me to give a type for React.useRef() but I don't know what to give it?

 const toastIdRef = React.useRef<WhatTypeShouldThisBe?>(null);

I am using chakra-ui/react v1.6.7 and typescript 4.2.4.

1 Answers

It seems it is either a string or a number:

const toastIdRef = React.useRef<number|string>(null);

Looks like you could import ToastId type:

Toast props

ToastId type

export type ToastId = string | number
import { useToast, ToastId } from "@chakra-ui/toast";

...

const toastIdRef = React.useRef<ToastId>(null);

Edit react-useref-for-chakraui-toast

Related