Can I pass data from one page to another as a State using Nextjs 13 App directory

672 views Asked by At

Using Nextjs 13 App Router, I want to pass previewData from MainComponent.jsx to Preview.jsx as a State. not through query or props. I Just want to pass data as a state from MainComponent.jsx and navigate to the Result.jsx receive the state data and display it in the Result Component. Is this possible, or is there a better approach to solve this problem?

My Folder Structure

-App
   -maincomponent
     -page.jsx
   -result
     -page.jsx

MainComponent.jsx

"use client";

import { useRouter } from "next/navigation";

const MainComponent = () => {
  const router = useRouter();
  const { id } = router.query;

  const imageData = images.find((image) => image.id === parseInt(id));

  let previewData = null;
  if (imageData) {
    previewData = {
      id: imageData.id,
      title: imageData.title,
      imageUrl: imageData.imageUrl,
    };
  }

  return (
    <div>
      {previewData ? (
        <div>
          <h1>{previewData.title}</h1>
        </div>
      ) : (
        <div>
          <p>Loading...</p>
        </div>
      )}
    </div>
  );
};

export default MainComponent;

Result.jsx

import { useRouter } from "next/navigation";

const Result = () => {

  return (
    <div>
        Display the Preview Data Here as A state
    </div>
  );
};

export default Result;
1

There are 1 answers

2
Faizan Tariq On

okay what you need to do is use useContext hook and create an external state for your application. what I am trying to say is that create a new file in app directory and create a context and pass values to it and then wrap layout component with it like this: suppose your new file name is store.jsx

const yourContext = createContext();
const Store = ({children}) =>{
 <yourContext.Provider values={{yourvalues}}>
    {children}
 </yourContext.Provider>
}
export default Store;

Then in layout.jsx file

import Store from "./store";
export default function RootLayout({children}){
return <Store> {children} </Store> }

what this will do is that I will create a common state across your application and then where ever you want to call it you just need to use useContext hook in that page and your state can easily be accessible without being lost. give it a try