In the src folder of a shopping app that I made with react and react-router, I've got a JSON file containing basic info about some products.
In the app component, I import the data and assign to the local state and pass it via props to my child components for their usage.
export default function App() {
const [products, setProducts] = useState(require("./products.json"));
...
}
While all that worked, I want to trigger an event when the page gets reloaded and write the modified data from the state into the JSON file, so that the data is not lost.
window.onbeforeunload = () => {
console.log("Page Reloaded");
fs.writeFile("products.json", JSON.stringify(products), (ex) => {
if (ex) throw ex.message;
console.log("State copying successful.");
});
};
I can see the Page Reloaded
getting logged just for a moment before the page actually gets reloaded, but the data I wished to save remains unchanged.
I suspect the fs module isn't getting imported properly since I have logged it and got an empty object. I've tried importing it manually as well as calling it with the require function.
import fs from "fs";
Any help would be really appreciated.