Zack Lau
Zack Lau

Reputation: 9

Why does router.query is not working when used within app/ with page.js, but work when move to pages/ with index.js

router.query is null, when i tried to use it inside my app directory when i moved to new pages directory outside the app, it works but the file name should be change to index.js, that means the nextui component was unable to use outside the app directory...

//app/stores/[id]/page.js 

'use client'
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { db } from '../../../firebase';
import { doc, getDoc } from 'firebase/firestore';

function StoreDetailPage() {
  const [store, setStore] = useState(null);
  const router = useRouter();
  const { id } = router.query || {};

  useEffect(() => {
    const fetchData = async () => {
      try {
        if (!id) return;

        const storeDocRef = doc(db, 'users', id);
        const storeDoc = await getDoc(storeDocRef);
          
        if (storeDoc.exists()) {
          setStore(storeDoc.data());
        } else {
          console.error("No such store!");
        }
      } catch (err) {
        console.error("Error getting document: ", err);
      }
    };
    
    fetchData();
  }, [id]); // Run the effect when id changes

  if (!store) return <div>Loading...</div>;

  return (
    <div>
      <h1>{store.name}</h1>
      <p>Contact: {store.phoneNumber}</p>
      {/* Display other store details here... */}
    </div>
  );
}

export default StoreDetailPage;

when i tried to use searchParams, the id is also 'null'

'use client'
import React, { useEffect, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { db } from '../../../firebase';
import { doc, getDoc } from 'firebase/firestore';

function StoreDetailPage() {
  const [store, setStore] = useState(null);
  const searchParams = useSearchParams();
  const id = searchParams.get('id');

  useEffect(() => {
    const fetchData = async () => {
      try {
        console.log('id:', id);
        if (id) {
          const storeDocRef = doc(db, 'stores', id);
          const storeDoc = await getDoc(storeDocRef);

          if (storeDoc.exists()) {
            setStore(storeDoc.data());
          } else {
            // Display an error message to the user.
            alert('No store ID provided.');
          }
        } else {
          // Handle the case where the id variable is null.
        }
      } catch (err) {
        console.error("Error getting document: ", err);
      }
    };

    fetchData();
  }, [id]);

when i moved to pages/[id]/index.js , the id is defined, but if i use page.js, the NextUi component is working but the content is 404... Sorry I'm newbie please let me know what i can do to solve this problem.

//_app.js
import { NextUIProvider } from '@nextui-org/react';

function MyApp({ Component, pageProps }) {
  return (
    <NextUIProvider>
      <Component {...pageProps} />
    </NextUIProvider>
  );
}

export default MyApp;

//layout.js 
import './globals.css';
import { Inter } from 'next/font/google';
import { Providers } from '../pages/providers';
import NavbarSelector from '../components/NavbarSelector'; // Import NavbarSelector

const inter = Inter({ subsets: ['latin'] });

export const metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
};

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <Providers>
          <NavbarSelector /> {/* Use NavbarSelector */}
          {children}
        </Providers>
      </body>
    </html>
  );
}

//provider.js 

"use client"
// app/providers.js
import React from 'react';
import { NextUIProvider } from '@nextui-org/react';

export function Providers({ children }) {
  return (
    <NextUIProvider>
      {children}
    </NextUIProvider>
  );
}


//

package.json

my directory looks like this:

app

pages

I just want to keep using NextUI in my Nextjs Project, on both app and pages directory. the problem i faced now is the query id from my URL is not working (router.query // useSearchParams) in my app/ directory with page.js name. But it works on pages directory with 'index.js' file name.

Upvotes: 0

Views: 115

Answers (1)

Youssouf Oumar
Youssouf Oumar

Reputation: 46161

Within the app router, your page.js component gets passed a params object when it's in a dynamic segment. And this params would contain your dynamic route id, like so:

// app/stores/[id]/page.js 

export default function StoreDetailPage({ params }) {
  const { id } = params;

  return <div>{id}</div>;
}

And you can use the useParams hook in client components:

// app/SomeClientComponent.js

'use client';

import { useParams } from 'next/navigation';

export default function SomeClientComponent() {
  const { id } = useParams();

  return <div>{id}</div>;
}

Upvotes: 0

Related Questions