Search code examples
javascriptjsones6-promise

JS: Render value from json into HTML not working


I would like to print the value "task" of a JSON object into HTML. But I get an Error. Thanks for any help in advance!

Code:

fetch('gamesets\\starter-content\\1.json')
    .then(data => data.json())
    .then(success => document.getElementById("gamecard-content").innerHTML = success.data[0].task);

Error:

app.js:143 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '0')
at app.js:143:90

JSON stored at gamesets\starter-content\1.json (path is correct in my setup)

[
    {
        "$schema":"v04cardSchema.schema.json",
        "author":"me",
        "task":"taskText"
    }
]

JSON Schema

    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "array",
    "items": [
      {
        "type": "object",
        "properties": {
          "author": {
            "type": "string"
          },
          "task": {
            "type": "string"
          }
        },
        "required": [
          "author",
          "task"
        ]
      }
    ]
  }

HTML (excerpt)

<p id="gamecard-content"> Waiting for cards to render... </p>

Solution

  • I think the problem is that you are trying to get data out of success argument but the success argument is actually is your data. And the reason for that is you are parsing a data in the previous then.

    Try doing this

    fetch('gamesets\\starter-content\\1.json')
      .then(data => data.json())
      .then(success => document.getElementById("gamecard-content").innerHTML = success[0].task);
    

    As you can see, I am accessing first element of an array on the success argument itself.

    Hope this helps.