I am trying taking an image input from the user in story route, then I pass it to the home route to display it, and of course the user can add as much as he need from the images, and that what I am seeking for. This is the related story route code:
const [fileStory, setFileStory] = useState([]);
const [selectedFile, setSelectedFile] = useState(null);
const router = useRouter();
const handleFile = (event) => {
setSelectedFile(event.target.files[0]);
};
const handleAddStory = () => {
setFileStory((previous) => {
const newImageList = [...previous, URL.createObjectURL(selectedFile)];
localStorage.setItem("imageList", JSON.stringify(newImageList));
router.push('/');
return newImageList;
});
setSelectedFile(null);
};
This is the related home route code:
const [images, setImages] = useState(localStorage.getItem("imageList") ? JSON.parse(localStorage.getItem("imageList")) : []);
return (
{images && images.map((imageUrl, index) => (
<div key={index} className="bg-white rounded-lg h-60 w-36 hover:brightness-95 shadow-md cursor-pointer">
<div className="bg-gray-400 flex h-3/4 rounded-t-lg">
<img src={imageUrl} alt="Story" width={200} height={200} className="rounded-t-lg" />
</div>
</div>
))}
)
Now let's go to the problem that I am facing, like I said before that the number of images that will be added is not going to be one, so every time user go to the story page, he select a new image, then I add that image to the fileStory variable "with the previous images", so that the previous added images will not be lost when the user tried to add the new image, then when returning to the home page it will display the previous images with the new image added to it, but unfortunately that is not happening, when trying to add new image it is only displaying the new one without the previous one, so I am loosing the previous images data, I do not know why this is happening.
You can use browser localStorage to store the previous page state and then using useEffect to fetch the data from localStorage to keep user input