skip to Main Content

Just for reference, I am creating a shopping cart for an e-commerce website following an old tutorial and updating it to Next.js 13+ as I code.

In the previous version of the tutorial, the _app.ts file was using page routing. The code snippet looked like this:

return (
  <>
    <Navbar cart={cart} addToCart={addToCart} removeFromCart={removeFromCart} />
    <Component cart={cart} addToCart={addToCart} removeFromCart={removeFromCart} {...pageProps} />
  </>
);

Now, with the new App Routing in Next.js 13+, I have the following code in the layout.ts file using app routing:

return (
  <html lang="en">
    <body className={inter.className}>
      <Navbar cart={cart} addToCart={addToCart} removeFromCart={removeFromCart} />
      {children} {/* <-- Alternative code to pass props? */}
    </body>
  </html>
);

Are there any other ways to pass props in this new setup, apart from using Redux. Any guidance or suggestions would be greatly appreciated.

2

Answers


  1. Chosen as BEST ANSWER

    useContext did the work for me. Redux seemed overkill and there were no other ways to pass props (as per the replies). I wanted to update the states globally so fetching data doesn't work.


  2. According to the App Router documents:

    https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts

    Passing data between a parent layout and its children is not possible. However, you can fetch the same data in a route more than once, and React will automatically dedupe the requests without affecting performance.

    This is an example of how they want you to fetch data in the page.tsx file:

    async function getData() {
      const res = await fetch('https://api.example.com/...')
      // The return value is *not* serialized
      // You can return Date, Map, Set, etc.
     
      // Recommendation: handle errors
      if (!res.ok) {
        // This will activate the closest `error.js` Error Boundary
        throw new Error('Failed to fetch data')
      }
     
      return res.json()
    }
     
    export default async function Page() {
      const data = await getData()
     
      return <main></main>
    }
    

    Data fetching is mainly based around using fetch(). But you can see a lot more examples of what is doable here:
    https://nextjs.org/docs/app/building-your-application/data-fetching/fetching

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search