#Flash Message

1 messages · Page 1 of 1 (latest)

proven fog
#

im trying to show a message using a toast before a redirect? how do i it? for example: i want to call a toast() after a successful call from a serveraction and it will redirect to /product page

strange compassBOT
#

Hi @proven fog. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the information provided in the extracts, you can use the useState hook from React to manage the state of your toast notification. Here's an example of how you might do this:

import { useState } from 'react'

export default function Page() {
  const [message, setMessage] = useState<string>('')

  async function onCreate(formData: FormData) {
    const res = await create(formData)
    setMessage(res.message)
    // Insert your toast function here
    toast('Your message')
    // Then perform the redirect
    redirect('/product')
  }

  return (
    <form action={onCreate}>
      <input type="text" name="item" />
      <button type="submit">Add</button>
      <p>{message}</p>
    </form>
  )
}

In this example, setMessage is used to set the state of the message that will be displayed in the toast notification. The toast function would be where you handle displaying the toast notification. After the toast notification is displayed, you can then use the redirect function to redirect to the /product page.

Please note that the redirect function in Next.js is a server-side utility and it throws a NEXT_REDIRECT error to signal a redirect. This error should be allowed to propagate and should not be caught in a try-catch block, as it's used by Next.js to stop the execution of the current route and perform the redirect (source (https://github.com/vercel/next.js/issues/50757)).

Also, please note that the redirect function in Next.js is a temporary (307) redirect, while permanentRedirect is a permanent (308) redirect (source (https://nextjs.org/docs/app)).

#

This is a basic example and you might need to adjust it based on your specific use case and the library you're using for toast notifications.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: