Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add callback after toast function execute #63

Open
momosetti opened this issue Apr 4, 2021 · 9 comments
Open

Add callback after toast function execute #63

momosetti opened this issue Apr 4, 2021 · 9 comments
Labels
enhancement New feature or request

Comments

@momosetti
Copy link

No description provided.

@timolins
Copy link
Owner

timolins commented May 31, 2021

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

@quiin
Copy link

quiin commented Jul 5, 2021

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
Copy link

quiin commented Jul 5, 2021

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: () => {}})

@ecfaria
Copy link

ecfaria commented Nov 15, 2021

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.

@timolins timolins added the enhancement New feature or request label Nov 24, 2021
@maciekgrzybek
Copy link

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

@pamojadev
Copy link

@maciekgrzybek did you find anyway to achieve this?

@maciekgrzybek
Copy link

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

@kpratik2015
Copy link

kpratik2015 commented Dec 9, 2022

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') })

@jaguardo
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

8 participants