timolins / react-hot-toast

Smoking Hot React Notifications 🔥
https://react-hot-toast.com
MIT License
9.44k stars 309 forks source link

How can i pass dynamic variable to toast.promise loading? #321

Open klmntv opened 8 months ago

klmntv commented 8 months ago

something like this

toast.promise(
  myPromise,
  {
    loading: loadingProgress, // from useState hook for example
    success: 'Success',
    error: 'Error',
  },
)
nakamuraos commented 6 months ago

My solution is to use useRef.

This is implement example:

import { useRef } from "react";

const MyComponent = (props: any) => {
  const textRef = useRef<HTMLSpanElement>(null);

  const updateText = (text: string) => {
    if (textRef?.current) textRef.current.innerText = text;
  };

  const onHandle = async () => {
    updateText("Initiating...");
    await delay(3000);

    updateText("Optimizing images...");
    await delay(3000);

    updateText("Saving...");
  };

  const onClick = () => {
    toast.promise(onHandle(), {
      loading: <span ref={textRef}>Saving...</span>,
      success: "Successfully!",
      error: (error) => {
        console.log(error);
        return "Something were wrong.";
      },
    });
  };

  return (
    <div>
      <button onClick={onClick}>Show me</button>
    </div>
  );
};