What is the best way to display toasts in React server components?

I am currently working with Next.js 14 and utilizing the app router for my project.

Within my application, I have two server components:

  1. A List page located at /products, which displays multiple products
  2. A Product Details page located at /products/{id}.

On the /products/{id} page, I perform a check to see if the specific id exists in my products database using a server action and then proceed to display the product details.

In cases where the product is not found, my intention is to redirect the user back to the /products page and display a toast message indicating that the product could not be located.

The redirection process is straightforward:

import { redirect } from 'next/navigation'

async function getNoProduct() {
  return null
}

export default async function RedirectFromPage() {
  
  let res = await getNoProduct()
  if (!res === null) {
    redirect('/products')
  }
  return (
    <div>
      <p>Hello SO</p>
    </div>
  )
}

However, I am facing challenges when trying to implement the toast message (using sonner toast via shadcn).

Directly adding the toast as shown below does not work because /products/{id} is a server component and the toast functionality relies on useEffect:

import { redirect } from 'next/navigation'
import { useToast } from '@/components/ui/use-toast'

async function getNoProduct() {
  return null
}

export default async function RedirectFromPage() {
  const { toast } = useToast()

  let res = await getNoProduct()
  if (!res === null) {
    // Show toast
    toast({
      title: 'Error',
      description: 'Product not found',
    })
    redirect('/products')
  }
  return (
    <div>
      <p>Hello SO</p>
    </div>
  )
}

This setup will result in an error stating:

Error: useState only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/react-client-hook-in-server-component

After looking into a similar question regarding server actions on Stack Overflow (here), I considered using cookies to communicate the error back to the /products page and then render a client component that includes the toast feature. However, I encountered issues due to the fact that these server actions can only be triggered from a client component (source).

Given this situation, how should I approach integrating the toast functionality? Is using toast simply not suitable for this scenario, or is there a more effective way to achieve this desired outcome?

Answer №1

From my perspective, it seems that toast packages are designed for use on the client side. When it comes to server-side functionality, you could consider creating a loading.tsx page in Next.js to display a loading screen before rendering the intended page. If you have a client-side component within a server-rendered page, React Suspense may be used to encapsulate the client-side component within the server-rendered page.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered an error during the production build of NEXTJS, where it panicked due to the global thread pool not being initialized

While hosting my app on Heroku and running git push heroku main, I encountered the following error: panicked at 'the global thread pool has not been initialized.: threadpool builderror { kind: ioerror(error { kind: unsupported, message: "operatio ...

`End session for inactive user after next authentication`

I am facing a challenge with managing inactive user sessions in my app. I tried setting the maxAge of ...nextauth to one minute and the refetch interval to 20s for SessionProvider, but encountered an issue where the session expiration on the browser cook ...

What is the reason behind the necessity of passing a specific route argument for on-demand Incremental Static Regeneration to work in Next.js?

After reviewing the documentation and official videos from Vercel, I noticed that in the revalidate API, they sometimes call res.unstable_revalidate('/') with just a slash to potentially revalidate the entire application. However, there seems to ...

The Typescript error occurs when trying to assign a 'string' type to a 'SetStateAction<null>'

For my project, I am delving into creating a global context using TypeScript. As a newcomer to TypeScript, I found a helpful guide in this blog post (). Despite following the outlined steps, I keep encountering an error message saying "Type 'string&ap ...

What are the necessary steps to launch Next.js without relying on Vercel's platform?

Looking to deploy a Next.js app, but not on Vercel. What is the process for deploying it? In the past, I would drag and drop the build folder from React to the server, but with Next.js I am unsure of which files need to be deployed and how. Note: I am ut ...

Incorporate the block-input feature from sanity.io into your next.js blog for enhanced functionality

Currently, I'm in the process of creating a blog using next.js with sanity.io platform. However, I am facing some difficulties when it comes to utilizing the code-input plugin. What's working: I have successfully implemented the code component b ...

How can you ensure that only one dropdown is active at a time while keeping others inactive in a React component

I'm currently working on implementing a dropdown navigation feature. The goal is to ensure that only one dropdown remains open at a time when clicked, and all others should close automatically. However, I've run into an issue where both dropdowns ...

What could be causing the flickering in Next.js?

I have noticed an unusual flickering behavior on some of the pages on my website. Here is a breakdown of what occurs: The page briefly appears. The white screen vanishes and is replaced. The fully rendered page finally shows up. I am looking for a soluti ...

Testing next-i18next localization with useTranslation in Jest

Exploring testing libraries is always an interesting adventure. In my NextJS project, I'm utilizing next-i18next. We're incorporating the useTranslation hook with namespaces. During testing, a warning pops up: console.warn react-i18next:: You ...

"Encountered a 'NextAuth expression cannot be called' error

Recently, I delved into learning about authentication in Next.js using next-auth. Following the documentation diligently, I ended up with my app/api/auth/[...nextauth]/route.ts code snippet below: import NextAuth, { type NextAuthOptions } from "next-a ...

Using the fetch/await functions, objects are able to be created inside a loop

In my NEXTJS project, I am attempting to create an object that traverses all domains and their pages to build a structure containing the site name and page URL. This is required for dynamic paging within the getStaticPaths function. Despite what I believe ...

Sharing context sub files in Next.js can be easily accomplished by following a few simple

These are the pages on my website: /pages /gift /[slug] index.tsx /personalize index.tsx In /gift/[slug]/index.tsx, I have a component called GiftProvider that looks like this: return ( <GiftProvider gift={gift}& ...

Using Next Js for Google authentication with Strapi CMS

Recently, I've been working on implementing Google authentication in my Next.js and Strapi application. However, every time I attempt to do so, I encounter the following error: Error: This action with HTTP GET is not supported by NextAuth.js. The i ...

Nextjs 13 Application Folders with a Progress Bar

Currently utilizing the Next.js 13 app directory and I am looking to incorporate a progress bar for when users navigate between pages. I have been unable to find a solution online as it seems to only work with simple Next.js projects and not within the app ...

Why does the page I navigate from always trigger loading?

I am currently working on a web application using Next.js 13 with app routing. The issue I'm encountering is that when transitioning from the /projects page to the /projects/:id/edit page, it triggers loading events for both pages. However, I would li ...

What is the best way to handle asynchronous actions while initializing a database in Next.js?

My goal is to create tables during the database initialization stage with a structure like this: CREATE TABLE IF NOT EXISTS users ( "id" SERIAL PRIMARY KEY, "created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "name&quo ...

Creating movement in an SVG patterned background

Currently in the process of designing a brand new website using NextJS and Tailwind. I am looking to incorporate an infinitely translating background effect that moves towards the bottom right, similar to this example (but with my own unique pattern): htt ...

Is it acceptable to use JavaScript files in the pages directory in NEXTJS13, or is it strongly advised to only use TypeScript files in the most recent version?

In the previous iterations of nextJS, there were JavaScript files in the app directory; however, in the most recent version, TypeScript files have taken their place. Is it still possible to begin development using JavaScript? I am working on creating an a ...

Guide to setting up App Check in a development environment and launching your next js 13.4 project with an app folder and integrating reactfire

Having trouble integrating "firebase app check" into a Next.js 13.4 project that has the "app" directory in development mode. I attempted to use ReactFire but kept running into errors. Since the latest version of Next.js is in SSR, I tried using effects to ...

Version 13 of NextJS seems to be experiencing issues with the onClick event, but fear not as the component is utilizing the 'useClient

I was attempting to incorporate the select component into my project when I encountered an issue with the onClick function. It seems that it was not working properly, even though I made use of 'use client;' for my component. "use client" ...