Updating the sidebar server component in a messaging application using NextJS 13

For a complete minimal reproducible repository, visit this link.

This application is a chat app that features the following routes:

  • /chat
    • layout.tsx - server component containing the Sidebar which is also a server component
  • /chat/[id] - client component

Despite trying all of the commands listed below, I have been unable to update the sidebar when changing data in my Input component:

router.refresh();
router.push("/chat/" + chatId);

Even after implementing a route specifically designed to invalidate the cache on the server side with the function call

revalidatePath("/chat", "layout")
, the sidebar still fails to update.

Interestingly, although my Sidebar server component indicates that it updates, the UI itself does not reflect these changes.

Below are excerpts of key code snippets, while the full reproducible code can be found in the provided repository.

// ./app/chat/layout.tsx

import React from 'react'
import { Sidebar } from "./_sidebar"

export default async function Layout({children}: {children: React.ReactNode}) {
  return (
    <div className="relative w-screen min-h-screen flex justify-start">
      <Sidebar />
      {children}
    </div>
  )
}
// ./app/chat/_sidebar
import { getChats } from "@/actions";
import Link from "next/link";

export async function Sidebar() {
  const chats = await getChats();
  console.log("Sidebar.chats.latest", chats.at(-1))

  return (
    <div className="flex flex-col h-full px-6 min-h-screen">
      <h2 className="font-bold underline">Sidebar</h2>
        <Link href="/chat">New Chat</Link>
        {chats.map((chat, index) => (
          <p className="whitespace-nowrap" key={index}>{chat.message.slice(0,20)}</p>
         ))}
    </div>
  );
}
// ./app/chat/_input.tsx

"use client";
import { nanoid } from "nanoid";
import { useRouter } from "next/navigation";
import React from "react";

export function Input() {
  const router = useRouter();
  const inputRef = React.useRef<any>();

  return (
    <div className="absolute bottom-1/2 flex flex-col h-28">
      <div className="flex flex-col space-y-8">
        <label className="text-white">Input Field Below:</label>
        <textarea ref={inputRef} className="text-black w-96 h-48" />
        <button
          className="bg-green-900 px-6 py-3"
          onClick={async () => {
            const value = inputRef?.current.value;
            const chatId = nanoid();
            await fetch("/api/chats/update", {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify({ id: chatId, message: value }),
            }).then(res => res.json());

            await fetch(`/api/revalidate?path=/chat&type=layout`, {cache: "no-store"});
            router.refresh();
            router.push("/chat/" + chatId);
         }}
        >
          Submit
        </button>
      </div>
    </div>
  );
}

Answer №1

After some experimentation, I discovered a workaround: reversing the order of router.push and router.refresh statements seems to resolve the issue. It also appears that calling revalidatePath may not be necessary in this case.

Here is an example of the modified code:

<button
    className="bg-green-900 px-6 py-3"
    onClick={async () => {
        const value = inputRef?.current.value;
        const chatId = nanoid();
        await fetch("/api/chats/update", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({ id: chatId, message: value }),
        }).then(res => res.json());
        router.push("/chat/" + chatId);
        router.refresh();
    }}
>
    Submit
</button>

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

Facing an "Invalid hook call" error in the NX monorepo with Next.js when trying to utilize jotai

Encountering a pesky "Invalid hook call" error while working on a Next.js app within an NX workspace. I've prepared this CodeSandbox. The start command fails when executed automatically, so manual rerun may be required. To replicate the issue, these ...

Error with SWR hook: "Fetcher argument not supplied"

Using the SWR hook for the first time, everything is working smoothly so far. However, I've encountered an error that I can't seem to figure out. Let me share my code with you. This is the global configuration: <AuthContext> {isValidRo ...

Guide to dividing a URL in reactjs/nextjs

Here is the complete URL: /search-results?query=home+floor&categories=All+Categories. I am looking to separate it into two sections - /search-results and query=home+floor&categories=All+Categories. My objective is to extract the second part of t ...

Ways to transform information with SWR

I have developed two essential functions to manage data retrieval and manipulation. The first function is responsible for retrieving all quotes, handling mutations, and indicating loading status. // Fetcher and the baseUrl export const baseURL = 'http ...

Encountering an issue while attempting to implement Redux Toolkit alongside the MUI ToggleButtonGroup component

The error message initially started as: Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. When I attempted to update the Redux state using a dispatcher, the handleChange function suddenly showed an e ...

Efficient Individual Messaging

During my attempt to incorporate one-to-one messaging in NextJS using Ably, I hit a roadblock. I'm torn between creating channels for interactions (such as private:<user_1>-<user_2>) and channels for individual users (like private:<use ...

The issue with Tailwind styles not being properly applied in subpages of Next13

Just started using NextJS today and I'm excited to incorporate Tailwind CSS along with it by following this article from the NextJS documentation. Everything seems to be working fine when I use Tailwind in the main / directory, but as soon as I navig ...

How can Next.js 14 implement sending fingerprint data from the client to the server with every request?

I am capturing a user's fingerprint in the browser using the following code: "use client" import FingerprintJS from "@fingerprintjs/fingerprintjs" import { useCookies } from "next-client-cookies" import React from " ...

The latest version of Next.js, 11.1.0, does not support monitoring for code changes within the node

In the latest version of Nextjs (11.1.0), there seems to be an issue where code changes in the `node_modules` directory are not being watched, unlike in the previous version (10.2.1). While working on a project with Nextjs 11.1.0, I have tried explicitly ...

The Swiper example is not compatible with the default settings of Next 13

Swiper is not compatible with Next 13. Using the default React example of Swiper + 'use client' at the top of the page does not yield the expected results. To replicate the issue, follow these steps: Create a bare-bones Next 13 app using this ...

Struggling to publish my Next.js app on Vercel. Any suggestions on how to proceed?

I have been facing an issue with my Next.js project. It runs smoothly on localhost, but I encountered a problem when trying to deploy it on Vercel. Below are the errors that I received: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! ...

Exploring the functionality of multiple checkboxes in Next.js 14, the zod library, shadcn/ui components, and react-hook

I'm currently working on a form for a client where one of the questions requires the user to select checkboxes (or multiple checkboxes). I'm still learning about zod's schema so I'm facing some challenges in implementing this feature. I ...

The link appears to be broken when trying to access the notFound component in Next.js version 13

In my Next.js 13.4 app directory, I added a not-found.tsx component that functions correctly when entering the wrong route: import Link from 'next/link' function NotFound() { return ( <section> 404, page not found ...

What steps should I take to resolve the 'Expected 1 arguments, but got 2.ts(2554)' error, so that I can successfully publish a post on firebase with an image URL?

The purpose of this RTkQuery endpoint is to create a post in Firestore. It requires two parameters: post and file, and utilizes the addDoc() and updateDoc() functions to carry out this operation. If a file is provided, the endpoint will upload the file to ...

Creating a task list without using JavaScript in the web browser and without relying on a database

Looking for some guidance on building a todo app for a job interview where JavaScript is disabled in the browser and no database can be used. Any JavaScript needs to be handled on the server side. I have some basic knowledge of node/express and serving H ...

Problem with deploying NextJs on Vercel

I've encountered an issue when trying to deploy to Vercel by pushing code to the main branch since yesterday. Every page on my website (404, homepage, etc.) is displaying a strange error message, even though there are no instances of the useID() hook ...

I encountered a warning while using the useViewportScroll in NextJs with Framer Motion: "Caution: The useLayoutEffect function does not have any effect on the server

Successfully implementing NextJs with Framer Motion, yet encountered a warning: Warning: useLayoutEffect does not function on the server due to its effect not being able to be encoded in the server renderer's output format. This may cause a differenc ...

Encountering a NextJS pre-render issue while generating the sitemap.xml

While developing my markdown-based blog, everything functioned smoothly in the developer environment. However, when I attempted to build the project using the command npm run build, I encountered an error related to pre-rendering failure. Error occurred pr ...

having trouble loading marker in react leaflet within next.js

I am facing difficulty in implementing react leaflet Marker in my next.js project. Below is the code snippet where I have included my map component: const MapSearch = dynamic(import('../../components/Map'), { ssr: false, loading: () => ( ...

Experiencing issues with Sendinblue integration on Vercel's production environment

It's the typical scenario - everything runs smoothly during development but throws errors in production without any clear explanation. My NextJS app is deployed on Vercel. I attempted to incorporate async await into my code based on a recommendation ...