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;
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
Then in layout.jsx file
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