Add an array to a HTML dataset

PHOTO EMBED

Sat Dec 24 2022 05:07:10 GMT+0000 (Coordinated Universal Time)

Saved by @davidmchale #array #dataset #html

import "./styles.css";

const date = new Date();
const root = document.getElementById("app");
root.setAttribute("data-posts", "[]");

const items = [
  {
    title: "book 1",
    author: "David",
  },
  {
    title: "book 2",
    author: "Kevin",
  }
];

const posts = () => {
  setTimeout(() => {
    let outPut = `<ul>`;
    for (let item of items) {
      outPut += `<li>${item.title}</li>`;
    }
    outPut += `</ul>`;
    root.innerHTML = outPut;
  }, 500);
};



const createPost = (post, callback) => {
  const item = {
    title: post.title,
    author: post.author,
  };

  items.push(item); // push the item to the items array
  callback(); //evoke the callback function

// set the posts data attribute to take in all the items
  root.dataset.posts = JSON.stringify(items);
};

console.log(
  createPost({ title: "book 3", author: "Derek"}, posts)
);
content_copyCOPY