'How can I show a Chakra-UI Toast programmatically?

I'm attempting to show a Chakra-UI Toast programmatically using the Chakra-UI React.js component library and am struggling to get it to work. The Chakra-UI Toast documentation only shows how to show the toast based on a button click, but I'd like to display it programmatically - in a returned promise after an AJAX call is made. I'm not sure if it's feasible, but I'd like to have a showToast function I could call to show it.

I'm in the process of integrating Chakra-UI into a React.js web application and am fairly new to both React.js and Chakra-UI.

Update

Here is a CodeSandbox showing what I am trying to achieve: https://codesandbox.io/embed/upbeat-rhodes-9zkii. I have a button in there that shows the toast when it's clicked, but I'd like to show it in the setTimeout where the TODO is located.



Solution 1:[1]

Heres my solution, just in case someone stumbles accross this thread:

import { useToast } from "@chakra-ui/react";
import { useState, useEffect } from "react";

export function useToastHook() {
  const [state, setState] = useState(undefined);
  const toast = useToast();

  useEffect(() => {
    if (state) {
      const { message, status } = state;

      toast({
        title: status,
        description: message,
        status: status,
        duration: 3000,
        position: "top",
        isClosable: true,
      });
    }
  }, [state, toast]);

  return [state, setState];
}

And to use is do this (you can also pass the the newToast to any function which isn't in a .jsx file):

import { useToastHook } from "../components/Toast";

const App = () => {
  const [state, newToast] = useToastHook();

  const someThingHappens = (message) => {
    newToast({ message: message, status: "error" });
  };

  return (
    <div>
    ......
   </div>
  );
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 saferugdev