Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write data to JSON file while using Reactjs

Or actually the question should be

How to write data to JSON file using Reactjs and Nodejs

I'm very first to react and do not understand which database should I use with.

PS. It's can easily to read json file with

var data = require('./data.json');

but to write data I try using npm 'jsonfile' package and both try to used Nodejs and got this error

TypeError: fs.writeFileSync is not a function

like image 410
Noer Nova Avatar asked Nov 08 '22 19:11

Noer Nova


1 Answers

I was literally searching for an answer on this today. I'm using React so it should be similiar for you. I think I figured it out.

I found you have to do two things.

  1. Import the Json file at the top of your code file

    import data from ./data.json

  2. Declare a variable passing the name of the variable specified in the import statement(in this case data)

    const data = require('./data.json');

Now calling {data} should allow you to usae the data of the file

Hope this helps :D

like image 151
Vincent Morris Avatar answered Nov 14 '22 21:11

Vincent Morris