timolins / react-hot-toast

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

toast.loading() not working with nextjs 14 #324

Open MauricioKruijer opened 1 year ago

MauricioKruijer commented 1 year ago

Hi there, thanks for releasing this amazing product!

I would like to use it in my nextjs project and I'm running into a few issues with toast.promise() and toast.loading(). I am trying to disable a submit button -> show loading toast -> await my action -> show success (or error). Which would be the expected behaviour, however, I only get the loading toast only the second time I click the button. The success toast is more consistent.

Please have look at https://github.com/MauricioKruijer/nextjs-react-hot-toast/commit/fb8db5a7126b3b7b84c4f8651c6349394b72c6fb for more information. You can run this project to experience what I'm talking about.

There is an extract of my form that is trying to render the toast by using useFormState()

'use client'

import Button from "@/components/Button";
import {useFormState} from "react-dom";
import toast from "react-hot-toast";

function doStuff(formData: FormData) {
  // if (Math.floor((Math.random() * 4) + 1) === 1) {
  //   throw new Error('This is a planned error')
  // }
  return new Promise(resolve => setTimeout(resolve, 1500))
}

async function someAction(state: any, formData: FormData) {
  const toastId = toast.loading('Loading') // This toast is not not shown, sometimes on third or second time of hitting the button

  try {
    await doStuff(formData)
  } catch (error) {
    toast.dismiss(toastId);
    toast.error((error as Error).message)
    return {
      errors: 'something went wrong'
    }
  }

  toast.success('Success!', {id: toastId})

  return {
    message: 'ok'
  }
}

const Form = () => {
  const initialState = { message: null, error: null };
  const [state, dispatch] = useFormState(someAction, initialState);

  return (
    <form action={dispatch}>
      <Button />
    </form>
  )
}

export default Form
tszhong0411 commented 10 months ago

It seems that this project has been abandoned. Here is a minimal reproduction that there is a difference between triggering by click and form action when using react-hot-toast.

I tested that this is a problem only when using react-hot-toast.

https://codesandbox.io/p/devbox/reac-hot-toast-test-lz39vl?file=/app/page.tsx

designbyadrian commented 10 months ago

It seems that this project has been abandoned.

Not abandoned: https://github.com/timolins/react-hot-toast/issues/298

bigblobby commented 8 months ago

Could you use onSubmit instead? This looks to be working.

As far as i'm aware you'd usually only use server actions in nextjs, i don't see why you'd need client actions.