1

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.

  • It seems that you cannot use fs with React https://stackoverflow.com/questions/35003961/react-js-require-fs because it is a node core module, if you would want to use you should set up a server – axtck Apr 27 '21 at 17:21
  • You expect to write to a file on the server from the client??? You need to make a call to some API that will update your `products.json`. That API will use `fs.writeFile`. Also, this question is not really about React. – Ruan Mendes Apr 27 '21 at 17:22
  • Got it, so is there any third-party lib, that can do the job? –  Apr 27 '21 at 17:24
  • No need for a 3rd party. You need to create an API endpoint, e.g, `POST /products` that takes JSON and writes it to that file. You may as well also create a `GET /products` instead of reading the file on the server to make your app [RESTful](https://en.wikipedia.org/wiki/Representational_state_transfer) – Ruan Mendes Apr 27 '21 at 17:27
  • 1
    That json as is is being injected into the built client-app, and as such any changes to the json file won't affect the client-app until you rebuild... so not only do you need a solution to updating the file, you need a solution to reading it. Effectively, from the client-app perspective, treat the json file as if it's just another data source. GET to retreive it from the server, POST/PUT to update it, let node.js do the work. – Kevin B Apr 27 '21 at 17:40

0 Answers0