0

I'm working with a JSON file in Javascript that I want to turn into single objects, where my next step is to have them in different cards in the HTML file.

API JSON file: http://jsonplaceholder.typicode.com/todos

I have fetched the API:

fetch("https://jsonplaceholder.typicode.com/todos")
    .then(function (response) {
        return response.json();
    })
    .then(function (json) {
    consoleLogJson(json);
    })
    .catch(function (error) {
        console.log(error);
    });

Then I have looped through the results of the JSON:

function consoleLogJson(json) {

const resultsContainer = document.querySelector(".results");
const results = json;

    for (let i = 0; i < results.length; i++) {
        console.log("<div>Title: " + results[i].title + "</div>" + "<div>UserId: " + results[i].userId + "</div>" + "<div>Id: " + results[i].id + "</div>" + "<div>Completed: " + results[i].completed + "</div>");
    }
}

This is my HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript - MA04 - Question 2</title>
<body>

<!-- Create a list of TODO cards using the API -->
<div class="results">


</div>

<script src="script.js"></script>
</body>
</html>

I am unsure what my next step should be.

ChrisM
  • 505
  • 6
  • 18
espen
  • 1
  • 1

2 Answers2

0

You're pretty much there, just change your console.log to instead append HTML to the results container. I would also recommend wrapping the html in a div (your to-do card). So change this part:

for (let i = 0; i < results.length; i++) {
    console.log("<div>Title: " + results[i].title + "</div>" + "<div>UserId: " + results[i].userId + "</div>" + "<div>Id: " + results[i].id + "</div>" + "<div>Completed: " + results[i].completed + "</div>");
}

To this:

for (let i = 0; i < results.length; i++) {
    resultsContainer.innerHTML += ("<div class='todo-card'><div>Title: " + results[i].title + "</div>" + "<div>UserId: " + results[i].userId + "</div>" + "<div>Id: " + results[i].id + "</div>" + "<div>Completed: " + results[i].completed + "</div></div>");
}
Jon Warren
  • 857
  • 6
  • 18
  • But how would I get the objects in the JSON file, in different cards? Thank u :) – espen Nov 03 '19 at 18:59
  • What is a card? The example I provided places the results in divs and attaches a class called 'todo-card' and renders it to the DOM. Can you please be a little more specific of exactly what you're trying to accomplish? – Jon Warren Nov 03 '19 at 19:37
0

Add HTML dynamically via parent.appendChild(child) and/or parent.innerHTML = htmlString. This is often done via plain strings or using a clone from template elements. To keep things simple, I'll show how to do things the "plain string" way. The rest of the work is likely to be in your CSS (I've included some example CSS that displays HTML content as cards).

Tips:

;(async () => {
  // Reusable function to fetch JSON resources (and error when not ok)
  const fetchJson = (...args) => fetch(...args).then(response => {
    if (!response.ok) throw new Error('Network response was not ok.')
    return response.json()
  })

  // Try to fetch data using the above function
  try {
    const todoArray = await fetchJson('https://jsonplaceholder.typicode.com/todos')
    
    // Map each todo item to some corresponding HTML
    const todosHTMLArray = todoArray.map(({ title, userId, id, completed }) => `
      <div class="card">
        <div class="card__detail">Title: ${title}</div>
        <div class="card__detail">UserId: ${userId}</div>
        <div class="card__detail">Id: ${id}</div>
        <div class="card__detail">Completed: ${completed}</div>
      </div>
    `)
    
    // Add all the new content from the HTML array above into the js-todos div
    document.querySelector('.js-todos').innerHTML = todosHTMLArray.join('')
  
  // Handle any errors
  } catch (error) {
    console.log(error)
  }
})()
:root {
  /* Sizes */
  --size-1: .5rem;
  --size-2: calc(var(--size-1) * 2);
  --size-3: calc(var(--size-1) + var(--size-2));
  --size-4: calc(var(--size-2) + var(--size-3));
  
  /* Colors */
  --color-main-major: #ffffff;
  --color-main-minor: #fafafa;
  --color-main-contrast-major: #222;
  --color-main-contrast-minor: #cccccc;

  font-family: sans-serif;
}

body {
  background-color: var(--color-main-minor);
}

.card-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: var(--size-2);
  margin: 0 auto;
  max-width: 1024px;
}

.card {
  display: grid;
  gap: var(--size-1);
  padding: var(--size-3);
  border: 1px solid var(--color-main-contrast-minor);
  background-color: var(--color-main-major);
  box-shadow: var(--size-1) var(--size-1) var(--size-1) var(--color-main-contrast-minor);
}

.card__detail + .card__detail {
  border-top: 1px solid var(--color-main-contrast-minor);
  padding-top: var(--size-2);
}
<div class="js-todos card-list"></div>
BCDeWitt
  • 4,540
  • 2
  • 21
  • 34