react-hot-toast icon indicating copy to clipboard operation
react-hot-toast copied to clipboard

Add callback after toast function execute

Open momosetti opened this issue 3 years ago • 9 comments

momosetti avatar Apr 04 '21 03:04 momosetti

Can you elaborate what your use-case is? Toasts are dispatched immediately so I don't see the point of having a callback.

timolins avatar May 31 '21 14:05 timolins

I found this issue while looking for a callback for when the toast is dismissed. My use case is:

  1. The user clicks a submit button attempting to submit invalid data
  2. The component's error state changes
  3. toast.error(error) is triggered and correctly displayed
  4. I need a way to set the error back to null (original state) after the error toast is no longer on screan because subsequent clicks are not triggering the error when it should.
import { useForm, Controller } from 'react-hook-form';

export default function MyApp() {
  const router = useRouter();
  const { signup } = useAuth()
  const loadingToast = useRef(null);
  const [error, setError] = useState(null);
  const [isSigninUp, setIsSigningUp] = useState(false);
  const { register, handleSubmit } = useForm({ mode: 'onChange' })

  // Display error message if any.
  useEffect(() => error && toast.error(error, { duration: 5000 }), [error])

  // Display loading indicator when user is signing up.
  useEffect(() => {
    if (isSigninUp) {
      loadingToast.current = toast.loading('We are creating your account...', { style: { color: 'green'}})
    } else {
      loadingToast.current && toast.dismiss(loadingToast.current)
    }
  }, [isSigninUp])
 
  // data comes from react-hook-form
  const onSubmit = data => {
    setIsSigningUp(true);
    signup(data.email, data.password)
      .then(() => router.push(entryPoint))
      .catch(error => setError(error.message || 'Error creating your account.'))
      .finally(() => setIsSigningUp(false))
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register('email', { required: true })}>
      <input  type='password' {...register('password', { required: true })}>
      <input type='submit'>
    </form>
  )
}

quiin avatar Jul 05 '21 18:07 quiin

Since toast is executed immediately, I'm setting and clearing an interval with the same duration as the toast:

const ERROR_DURATION = 5000;

export default function MyApp() {
...
  // Display error message if any.
  useEffect(() => {
    if (error) {
      toast.error(error, { duration: ERROR_DURATION })
      const errorTimeout = setTimeout(() => setError(null), ERROR_DURATION)
      return () => clearTimeout(errorTimeout)
    }
  }, [error])
...
}

I still think a 'cleaner' solution can be achieved if a onDismiss callback is exposed on toast({onDismiss: () => {}})

quiin avatar Jul 05 '21 18:07 quiin

I've found this issue in a similar manner to @quiin. But in my case, I would like to set the error to null on my Redux store, as we are showing errors generated on some redux actions that aren't triggered by the user, but on page load. So for example, if a critical request fails on page load, we would be able to show it to the user. I really believe it's a good use case for this option.

ecfaria avatar Nov 15 '21 13:11 ecfaria

I also need something similar but on when the toasts are dismissed. Happy to look into it if it's fine with you ? :)

maciekgrzybek avatar Feb 18 '22 10:02 maciekgrzybek

@maciekgrzybek did you find anyway to achieve this?

pamojadev avatar Jun 02 '22 06:06 pamojadev

I didn't look into it, had to use another library

maciekgrzybek avatar Jun 02 '22 07:06 maciekgrzybek

Don't know if this approach has flaws but this works for me so far:

type AutoConfirmOptions = {
  onConfirm: () => void;
  /** @defaultvalue 5000 */
  delay?: number;
  /** @defaultvalue "Auto-confirming in 5 seconds" */
  subText?: string | null;
};

const autoConfirm = (confirmationText: string, options: AutoConfirmOptions) => {
  let timeoutId: NodeJS.Timeout | undefined = undefined;
  const {
    onConfirm,
    delay = 5000,
    subText = 'Auto-confirming in 5 seconds',
  } = options;

  /** To be used onDestroy if used in useEffect or equivalent */
  const cleanup = () => {
    clearTimeout(timeoutId);
    toast.dismiss(toastId);
  };

  const toastId = toast(
    () => (
      <div className='flex flex-col gap-4 rounded-xl p-1'>
        <div>
          <p className='font-medium'>{confirmationText}</p>
          {subText && (
            <p className='mt-1 text-xs italic'>Auto-confirming in 5 seconds</p>
          )}
        </div>
        <div className='flex gap-4'>
          <button
            onClick={() => {
              cleanup();
              onConfirm();
            }}
            autoFocus
          >
            Confirm
          </button>
          <button
            onClick={() => {
              cleanup();
            }}
          >
            Cancel
          </button>
        </div>
      </div>
    ),
    {
      duration: Infinity,
    }
  );

  timeoutId = setTimeout(() => {
    onConfirm();
    toast.dismiss(toastId);
  }, delay);

  return { toastId, cleanup };
};

autoConfirm('You opted to delete xxx', { onConfirm: () => console.log('"It is done." - Frodo') })

kpratik2015 avatar Dec 09 '22 20:12 kpratik2015

Don't know if this approach has flaws but this works for me so far: ... { duration: Infinity, } );

timeoutId = setTimeout(() => { onConfirm(); toast.dismiss(toastId); }, delay);

return { toastId, cleanup }; };

Good idea... wonder if there is any progress on an onDismiss functionality. I have a similar issue where I engage a button and it changes color when engaged and produces a toast... when the toast times out I dont have a way to then "un-engage" the button... have no knowledge of its properties (open or not).

I tried using const { toasts, pausedAt } = useToasterStore(); and then checking toasts in an useEffect (obviously not a good production code):

  useEffect(()=>{
    if (toasts.length===0){
      console.log(toasts)
      setShowButton(false)
    }
  },[toasts])

but there is a re-fire somewhere and it un-engages the button early, toasts.length goes to 0 even when the pop-up is still active... may be another issue.

jaguardo avatar Oct 12 '23 15:10 jaguardo