Code Monkey home page Code Monkey logo

Comments (9)

quiin avatar quiin commented on May 31, 2024 7

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

from react-hot-toast.

quiin avatar quiin commented on May 31, 2024 1

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

from react-hot-toast.

maciekgrzybek avatar maciekgrzybek commented on May 31, 2024 1

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

from react-hot-toast.

kpratik2015 avatar kpratik2015 commented on May 31, 2024 1

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

from react-hot-toast.

timolins avatar timolins commented on May 31, 2024

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

from react-hot-toast.

ecfaria avatar ecfaria commented on May 31, 2024

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.

from react-hot-toast.

pamojadev avatar pamojadev commented on May 31, 2024

@maciekgrzybek did you find anyway to achieve this?

from react-hot-toast.

maciekgrzybek avatar maciekgrzybek commented on May 31, 2024

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

from react-hot-toast.

jaguardo avatar jaguardo commented on May 31, 2024

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.

from react-hot-toast.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.