JSFiddle - React, Tailwind, and code Playground

by jlspake

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<span data-bind="text: JSON.stringify(data)"></span>
<br/>
<span data-bind="text: id"></span>

JavaScript

function viewModel() {
  const self = this;
  self.data = ko.observable();

  self.fetchResults = function() {
    const id = ko.observable(0);
    fetch("https://jsonplaceholder.typicode.com/photos/1")
      .then(function(response) {
        var contentType = response.headers.get("content-type");
        if(contentType && contentType.includes("application/json")) {
          return response.json();
        }
        throw new TypeError("Oops, we haven't got JSON!");
      })
      .then(function(data) {
        console.log(JSON.stringify(data));
        self.data(data);
        self.id(data.length);
      })
      .catch(error => console.error(error));
    return id;
  };
  
  self.id = self.fetchResults();
};

ko.applyBindings(new viewModel());