Next.js Discord

Discord Forum

Not getting updates in server component after client component modifies data

Answered
Andalusian Hound posted this in #help-forum
Open in Discord
Avatar
Andalusian HoundOP
Hello,
I'm relatively new to Next.js so please bear with me!

I have a client component CreateOrganization which allows the user to create an organization using a form. Here is the form submission portion of the code:
  const handleSubmit = async (e: React.FormEvent) => {
    
    // ... some form validations here

    const data = {
      userId: session?.user.id,
      orgData: orgData,
      audienceData: audienceData,
    };

    const response = await fetch("/api/create-organization", {
      method: "POST",
      headers: {
        "Content-Type": "applcation/json",
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
       // ... error handling
    } else {
      router.push("/dashboard");
    }
  };


The create-organization endpoint simply creates a new organization in the DB (using Prisma ORM).

When the user is redirected to the Dashboard (server component), I want to display all the user's organizations. The issue is that I only see the new organization if I refresh the page.
I have simplified the Dashboard component below:
// ...imports

const prisma = new PrismaClient();

export default async function DashboardPage() {
  const session = await getServerSession(authOptions);

  if (!session) {
    redirect("/login");
  }

  const userId = session.user.id;
  const name = session.user.name;
  const organizations = await prisma.organization.findMany({
    where: {
      userId: userId,
    },
  });
  const hasOrganiations = organizations.length > 0;

  return (
    <div>
        {organizations.map((org) => (
          <p>
            {org.name}
          </p>
        ))}
    </div>
  );
}


From what I read online, calling router.refresh() in the client component should be causing the server to update its data, but it didn't work for me. Anyone have any ideas?
Answered by Andalusian Hound
Fix: I had to add router.refresh() after pushing /dashboard to the router in my handleSubmit function. I was calling router.refresh() before pushing.
View full answer

1 Reply

Avatar
Andalusian HoundOP
Fix: I had to add router.refresh() after pushing /dashboard to the router in my handleSubmit function. I was calling router.refresh() before pushing.
Answer