Next.js Discord

Discord Forum

unable to initialize state with props sent from server component to client component?!

Unanswered
Cicada killer posted this in #help-forum
Open in Discord
Cicada killerOP
Been banging my head on this for a few hours now and haven't made any progress. I read the value off a cookie inside a server component and then pass that value to a child (client component). When I do so, the user prop is successfully rendered and logged as the user object {id: 1, name: "John Doe"}, but the client component's authUser, variable is just { token: "" }

If I then refresh the page everything is as I'd expect, but that is the only way I've found to make this work. I've tried all of the cache invalidation strategies I could find in the next docs, but am still coming up short. What am I missing here?

server component:
import { cookies } from "next/headers";
import jwt from "jsonwebtoken";

import { Inner } from "@/components/inner";

export const Outer = async () => {
  const token = (await cookies().get("jwt")?.value) || "";

  let user: any = {
    token,
  };

  try {
    user = jwt.verify(token, process.env.JWT_SECRET as string);
  } catch {}


  return <Inner user={user} />;
};

client component
"use client";

import { useState } from "react";

export const Inner = ({ user }: { user?: any }) => {
  console.log(user);

  const [authUser, setAuthUser] = useState(user);

  return (
    <pre className="text-green-200">
      {JSON.stringify({
        user,
        authUser,
      })}
    </pre>
  );
};

0 Replies