3

I'm student and new to JS.

I need help to solve a problem. I have a lot of information so I want to use a static JSON file (json.data) insted of a array. How do I use fetch? I checked some examples but don't understand how to get it work with my code. I would be very thankful for some help, I have been stuck on this for a week.

// Loop through all my properties to display info on page 2

let page2 = (hairdresser) => {
  let singleView = "<div>";
  for(prop in hairdresser){
    if(hairdresser.hasOwnProperty(prop)){
      singleView += `${hairdresser[prop]} </p>`;
    }
  }

  singleView += "</div>"
  document.body.innerHTML = singleView;
}
    
// handleData function for page 1 

let handleData = (hairdressers) => {
    let out = "<table>";
    hairdressers.forEach((hairdresser, index) => {
        out += "<tr>";

        const printableProps = ["time", "name", "price", "timeEst", "rating", "adress"];
        printableProps.forEach(prop => {
            if (hairdresser.hasOwnProperty(prop)) {
                let isName = prop === "name";
                out += `<td>
        ${isName ? `<a href="#" onclick='page2(${JSON.stringify(hairdresser)})'}>` : ""}  
          ${hairdresser[prop]}
        ${isName ? '</a>' : ""}
        </td>`;
            }
        });
        out += "</tr>";
    })
    out += "</table>";

    document.body.innerHTML = out;
}

fetch("/path/to/data.json").then(res => res.json()).then(handleData);

**My JSON file:**

  [
    {
    "name" : "Sax & Fön",
    "adress" : "Rådmansgatan 46",
    "zip" : "113 57 Stockholm",
    "time" : "12",
    "tel" : "08-522 389 20",
    "site" : "www.salongweb.se",
    "rating" : "(32)",
    "price" : "320 kr",
    "timeEst" : "30 min",
    "open" : "Öppet till 19.00 idag",
    "desc" : "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris"
    },

   {

    "name" : "Hårley Davidson",
    "adress" : "Rådmansgatan 45",
    "zip" : "113 57 Stockholm",
    "time" : "12",
    "tel" : "08-522 389 20",
    "site" : "www.salongweb.se",
    "rating" : "(32)",
    "price" : "320 kr",
    "timeEst" : "30 min",
    "open" : "Öppet till 19.00 idag",
    "desc" : "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris"
    }
]
  • What do you mean my `fetch` data? Do you want the JS to read file from your hard drive instead hard coding? JS do not have direct access to local drive unless given permission explicitly. This link may be helpful: https://stackoverflow.com/questions/7346563/loading-local-json-file – Arun May 18 '18 at 13:46
  • You may want to look up "Ajax" if you need to fetch external data using javascript – Cocoduf May 18 '18 at 13:48
  • Can you tell us what the problem you're having is? Have you tried something and had it fail? If so, tell us what you tried and what happened. If you don't even know where to start, what are the things you're confused by? What kinds of specific questions do you have about those examples you've looked at? – divibisan May 18 '18 at 13:49
  • @Erika what didn't work about the fetch() line above? As long as that `data.json` file's contents are identical to what you've posted in the `data` variable above (and that file is available to wherever you're running this JS), that fetch line should work. – BigBlueHat May 18 '18 at 14:36
  • See my edit above, that's how I tried to do. Maybe it's something missing in the JSON file or the code. –  May 18 '18 at 17:52
  • @Erika check the dev console (if you're in a browser) for network errors, etc. It should at least show that the fetch is (or is not) working. Knowing that status should help narrow things down for you. Hope that helps! – BigBlueHat May 18 '18 at 20:35
  • I can see in the console that the fetch isn't working. It says that server don't find URI. ( fetch("/path/to/data.json").then(res => res.json()).then(handleData); ) –  May 18 '18 at 20:53

1 Answers1

3

Fetch example.

fetch('https://api.myjson.com/bins/176t5e')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
        handleData(myJson);

  });

Old Answer You can use XMLHttpRequest.

Create a new XMLHttpRequest instance and call your handleData function inside onreadystatechange.

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        handleData(JSON.parse(xhttp.responseText));
    }
};
xhttp.open("GET", "yourJson.json", true);
xhttp.send();

I uploaded your json data here. And sample example.

a.u.b
  • 1,589
  • 10
  • 25
  • 1
    The OP is requesting information for the Fetch API ("How do I use fetch?") which is gradually replacing XMLHttpRequest() https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch as the recommended approach. – BigBlueHat May 18 '18 at 14:39
  • @BigBlueHat you're right. i'm sorry and updated my answer. – a.u.b May 18 '18 at 15:45