skip to Main Content

My goal is to display random posts for clients visiting a static website. The information of these posts is stored in a json file on the server where all other html, css, js files are stored as well. The task can be splitted into three parts

  1. Generate the json file (done)
  2. Load data from the json file (partially done)
  3. Modify the html content (partially done)

The produced json on ./posts/posts.json:

{
    "posts": [
      {
        "head": "Ship Post",
        "text": "Just some text"
      },
      {
        
        "head": "Holiday Post",
        "text": "Text about holidays"
      }
    ]
  }

JavaScript code and html:


<div class="card">
  <h2 id="rs-card-head-00"></h2>
  <p id="rs-card-text-00"></p>  
</div>

<script>           
  function change_title(){
                
    var json = fetch("./posts/posts.json").then(response => {return response.json();});

    document.getElementById('rs-card-head-00').innerHTML = json.posts[0].head;
    document.getElementById('rs-card-text-00').innerHTML = json.posts[0].text;
  }

  change_title()
</script>  

A similar script (replacing the html lines with console.log(json.posts[0].head) and console.log(json.posts[0].text)) works just fine in node.js

2

Answers


  1. fetch is asynchronous (it’s a promise that a request will be fulfilled or not) so you can’t assign the result to a variable because it will be undefined at the point where you try to use its value.

    You have a couple of options.

    1. Continuing to use then:

      async function changeTitle() {
        fetch('./posts/posts.json').then(response => {
          return response.json();
        }).then(data => {
          head.textContent = data.posts[0].head;
          para.textContent = data.posts[0].text;
        });
      }
      
    2. Using async/await:

      async function changeTitle() {
        const response = await fetch('./posts/posts.json');
        const data = await response.json();
        head.textContent = data.posts[0].head;
        para.textContent = data.posts[0].text;
      }
      
    Login or Signup to reply.
  2. Your code was missing the proper handling of promises. Fetch returns a promise and needs to be handled with then or async/await.

    You need to handle the asynchronous nature of the fetch function. You can use async/await to wait for the response and then change the HTML

    async function change_title() {
      var response = await fetch("./posts/posts.json");
      var json = await response.json();
    
      document.getElementById('rs-card-head-00').innerHTML = json.posts[0].head;
      document.getElementById('rs-card-text-00').innerHTML = json.posts[0].text;
    }
    
    change_title();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search