0

I was trying to make a component which would dynamically load, fetching data on the server when being called. Unfortunately, I'm stuck with this error and don't know how to get around it. enter image description here

Here's what I've tried: Let's say we have a standard Server page which also renders a client component.

export default function Home() {
  return (
    <main>
      <ClientComponent />
    </main>
  );
}

That same client component has a state, which once changed dynamically loads the component in question

"use client";
import { useState } from "react";
import dynamic from "next/dynamic";
export function ClientComponent() {
  const [state, setState] = useState(true);

  const toggleState = () => setState((prev) => !prev);
  return (
    <div>
      {state ? <span onClick={toggleState}>Hello</span> : <ServerComponent />}
    </div>
  );
}

const ServerComponent = dynamic(() => import("./ServerComponent"), {
  ssr: true,
});

The server component once loaded, should fetch data on the server and pass it down to another client component which would sort out that data.

import { AnotherClientComponent } from "./AnotherClientComponent";

async function fetchingData() {
  console.log("Hello server");
  return ["red", "green", "blue"];
}

export default async function ServerComponent() {
  const data = await fetchingData();
  return (
    <div>
      <span>Hello from the server</span>
      <AnotherClientComponent data={data} />
    </div>
  );
}
export function AnotherClientComponent({ data }: { data: string[] }) {
  return (
    <ul>
      {data.map((d, index) => (
        <li key={index}>{d}</li>
      ))}
    </ul>
  );
}

Console log "Hello server" doesn't run on the server and the client gets the error bellow. Now my question is, is something like this even possible? I need to fetch data from my db which obviously cannot run on the client, I've looked into server actions but it doesn't seem like something that fits this use case. For anyone willing to take a look here's the sandbox of the problem. I would really appreciate any help or idea on how to overcome this.

https://codesandbox.io/p/sandbox/twilight-architecture-7mn8r9?file=%2Fapp%2FServerComponent.tsx%3A11%2C33

EDIT: Error happens once you click "Hello"

Also in the link to which the error points to, Dan Abramov says to look for the end of react@ errors, unfortunately I have none of those.

Vojin
  • 83
  • 7

0 Answers0