Search code examples
javascriptjsonreactjsfrontendcreate-react-app

JavaScript access local json


So I have a JSON file with mock data:

{
  "name": "Harvey Specter",
  "location": "New York, USA",
  "picture": "",
  "likes": 121,
  "following": 723,
  "followers": 4433,
  "comments": [
    {
      "id": 0,
      "author": {
        "picture": "",
        "name": "Mike Ross"
      },
      "date": "",
      "body": ""
    },
    {
      "id": 1,
      "author": {
        "picture": "",
        "name": "Rachel Zein"
      },
      "date": "",
      "body": ""
    },
    {
      "id": 2,
      "author": {
        "picture": "",
        "name": "Louis Litt"
      },
      "date": "",
      "body": ""
    }
  ]
}

How do I access it through javascript, and display the data in my React SPA? Also, I would like to be able to change the data i.e. if I click the 'follow' button it increments followers in JSON.


Solution

  • How do I access it through javascript, and display the data in my React SPA?

    You can make a request using fetch method in order to obtain the data from your file.

    fetch("data.json")
        .then( (response) => {
          return response;
        }).then( (json) => {
          //do whatever
        });
    

    or a native javascript request using XMLHttpRequest.

    If you want to read from local file. use require statement.

    var data = require('../../data.json');
    for(var i = 0; i < data.length; i++) {
       //iterate data
    

    You can display data using render function when React component is initialized.

    Also, I would like to be able to change the data i.e. if I click the 'follow' button it increments followers in JSON.

    You can change the array object using javascript.

    obj["followers"]=parseInt(obj["followers"])+1
    

    and then save new object to server-side using fetch method.