What steps can I take to ensure my dynamic route functions correctly in NextJs?

// /home/[storeId]/layout.tsx
import prismadb from "@/lib/prismadb";
import { auth } from "@clerk/nextjs/server";
import { redirect } from "next/navigation";

export default async function DashboardLayout({
 children,
 params,
}: {
children: React.ReactNode;
params: { storeId: string };
}) {
const { userId } = auth();

if (!userId) {
redirect("/sign-in");
}
const store = await prismadb.store.findFirst({
 where: {
   id: params.storeId,
   userId,
 },
 });

if (!store) {
 redirect("/home");
}

return (
 <>
   <div>Navbar</div>
   {children}
 </>
);
}

//  /home/[storeId]/page.tsx
import React from "react";

const Dashboard = () => {
return <div>Dashboard</div>;
};
export default Dashboard;

//  /home/layout.tsx

import prismadb from "@/lib/prismadb";
import { auth } from "@clerk/nextjs/server";
import { redirect } from "next/navigation";

export default async function SetupLayout({
 children,
}: {
 children: React.ReactNode;
}) {
const { userId } = auth();

if (!userId) {
 redirect("/sign-in");
}

const store = await prismadb.store.findFirst({
 where: {
   userId,
 },
});

if (store) {
 redirect(`/home/${store.id}`);
}

return <>{children}</>;
}

//  /home/page.tsx

"use client";
import { useEffect } from "react";

import { useStoreModal } from "@/hooks/use-store-modal";

const Home = () => {
 const onOpen = useStoreModal((state) => state.onOpen);
 const isOpen = useStoreModal((state) => state.isOpen);

 useEffect(() => {
  if (!isOpen) {
   onOpen();
  }
 }, [isOpen, onOpen]);
 return null;
export default Home;

// /hooks/use-store-modal.tsx

import { create } from "zustand";

interface useStoreModalStore {
 isOpen: boolean;
 onOpen: () => void;
 onClose: () => void;
}

export const useStoreModal = create<useStoreModalStore>((set) => 
({
 isOpen: false,
 onOpen: () => set({ isOpen: true }),
 onClose: () => set({ isOpen: false }),
}));

enter image description here

https://i.sstatic.net/823tS4qT.png

I am facing issues with creating a dynamic route in my NextJs App within the "home" folder. I tried to implement a redirection to a store page based on the store id but encountered errors such as a 404 message or a client-side exception. While I was successful when implementing it at the project root level, I'm struggling to debug and resolve the issue within the home folder due to my limited experience with NextJs. Any assistance would be greatly appreciated. Thank you.

Answer №1

This code snippet is causing an infinite loop due to a common mistake:

 const onOpen = useStoreModal((state) => state.onOpen);
 const isOpen = useStoreModal((state) => state.isOpen);

 useEffect(() => {
  if (!isOpen) {
   onOpen();
  }
 }, [isOpen, onOpen]);

The issue here lies in adding a state value that changes to the dependency array of the same useEffect hook calling a function that manipulates that state. This setup triggers repeated re-renders, resulting in an endless cycle.

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

When utilizing the file-loader in Webpack with a function in the outputPath parameter, an EISDIR error occurs,

I am attempting to create a specific output format for my locale files in the form of _locales/[locale_shortcut]/[file].json To achieve this, I am utilizing the file-loader plugin within webpack. While the documentation mentions the use of a function with ...

The npm local server is serving up the incorrect project

As someone who is new to JavaScript development, I am seeking guidance on running a next.js project on my local machine. Within my /projects folder, there are multiple projects... /projects/project1 (SvelteKit) /projects/project2 (Next.js) Upon navigat ...

Connecting PlayHt with NextJs for seamless compatibility

I've been experimenting with combining the play.ht node module with nextjs. My aim is to establish an api endpoint in nextjs14 that can accept a text in the body and then utilize playht to convert the text into audio, sending it back as a response for ...

Is app.component.ts necessary in an Angular 2 project?

Currently diving into Angular 2 and have a burning question on my mind. Do I really need the app.component.ts file in my project? Each of my folders has its own component and template, so I'm debating if the main component is necessary or if I can rem ...

Error Encountered: Unable to locate angular/core module in Angular 2

I have encountered an issue while setting up a new Angular2 app from the quickstart folder on the Angular website. Despite following all suggested solutions, I am still facing errors. After running npm install, everything seems fine as I can see my node_mo ...

Set the styling of a div element in the Angular template when the application is first initialized

I have a question about this specific div element: <div class="relative rounded overflow-clip border w-full" [style.aspect-ratio]="media.value.ratio"> <img fill priority [ngSrc]="media.value.src || ftaLogo" ...

Angular 2 Component attribute masking

In my Angular 2 component called Foobar, I have defined a property named foobar: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-foobar', templateUrl: './foobar.component ...

Passing a variable from the second child component to its parent using Angular

Need help with passing variables between two child components Parent Component: deposit.component.html <div> <app-new-or-update-deposit [(isOpenedModal)]="isOpenedModal"></app-new-or-update-deposit> </div> Deposit Component ...

Gaining entry to a static member of an exported class in a module

I am facing an issue with my Typescript code snippet. The code is as follows: module MyModule { export class MyClass { static MyStaticMember : string; } } My requirement is to access this code from a separate file after compilation. I tri ...

Vue and TypeScript: The elusive 'exports' remains unidentified

Since switching my App.vue to utilize typescript, I am facing a compiler error: [tsl] ERROR in \src\main.ts(2,23) TS2304: Unable to locate the name 'exports'. If I have vue-serve recompile after making changes, I encounter t ...

What is the best way to immediately update react useState?

Whenever I invoke the fetchProducts function, I require the productPage state to be updated before proceeding to the next line of code as it's needed for subsequent operations. The issue lies in the fact that the state is only updated after the funct ...

Having trouble with Prisma nextauth after changing the user model name from User to XYZUser

In my current project, we are using Nextjs, Next-auth, Prisma adapter, and Supabase for user authentication. Everything was working smoothly when the database model was named 'User'. However, after changing the model name to 'WebUser', ...

Trouble implementing array filter in React component is a common issue

Hello everyone! I'm facing an issue with deleting an element from my useState array. I have the index of the element that I want to remove, and I've tried the following code snippet: const updatedArray = myArray.filter((item: any, index: number) ...

Issue encountered with Tailwind Color Classes not functioning correctly when triggered by a button click within NextJS and React Vite framework

Recently, I've developed a component showcasing the "Text Gradient" effect in Tailwind + React. The component comprises of 4 select dropdowns and a "randomize" button. Upon clicking the button or selecting an option from the dropdowns, the changes are ...

Issue with Angular 2 Observable testing: Trying to use setInterval in an async zone test is not allowed

I am currently in the process of testing a component that relies on a service for making asynchronous HTTP calls. The service returns an Observable, which is then subscribed to by the component. Snippet from the service code: getRecentMachineTemperatures ...

Sequelize's bulk synchronization process is ineffective

I am facing an issue with getting sequelize.sync() to function properly. When I call sync() for each model definition individually, it works perfectly fine. However, when trying to execute it from the sequelize instance itself, it seems like the registered ...

Safari on Mac/iPhone crashes when you click the back button on a Next.js page

On some versions of IOS, the context object is undefined. When checking the network tab, cached .json files in the browser disk cache may throw a "403" error when the back button is clicked. I have included a snapshot of the network tab for reference. The ...

Enhance accessibility in Next.js and React Bootstrap with a feature that allows users to easily customize the font

My goal is to develop a component that enhances accessibility by allowing users to change settings such as dark mode, higher contrast, and font size dynamically. Currently, I have created a bootstrap modal component where users can modify accessibility se ...

Leverage Sinon's fakeServer in combination with promises and mocha for efficient

Having an issue here: I need to test a method that involves uploading data to an AWS S3 bucket. However, I don't want the hassle of actually uploading data each time I run my tests or dealing with credentials in the environment settings. That's w ...

Switch up your Next.js game by altering the Div color of your header based on the active page!

In the Next.js project I've been working on, I created a simple Layout.js file with the code shown below: import { Fragment } from "react"; import Header from "./Header/Header"; import Footer from "./Footer/Footer"; fun ...