JSFiddle - React, Tailwind, and code Playground

by allananvil

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Your amazing app</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/picnic">
    <script src="main.js" async></script>
</head>
<body>
<div id="app">
    <div class="flex two">
        <div class="my-list">
            <h3>My List</h3>
            <div id="result"></div>
        </div>

        <div class="actions flex">
            <p>This button will call our API endpoint.</p>
            <button id="do-something" class="">Do it</button>
        </div>
    </div>
</div>

</body>
</html>

CSS

#app {
          padding: 20px 0;
          margin: 0 auto;
          width: 750px;
        }

        .actions {
          flex-direction: column;
        }

        .actions p {
          text-align: center;
        }

JavaScript

const API_URL = 'http://localhost:8000'
const button = document.getElementById('do-something')

function getResultEl () {
  return document.getElementById('result')
}

function handleResponse (response) {
  try {
    response = JSON.parse(response)
  } catch (e) {
    console.log({ error: e })
    response = []
  }

  const html = response.length
    ? response
      .map((item) => `<li>${item.name}</li>`)
      .join('')
    : '<li>Could not get response</li>'

  getResultEl().innerHTML = `<ul>${html}</ul>`
}

button.onclick = (event) => {
  const xhr = new XMLHttpRequest()
  xhr.open('GET', `${API_URL}/items`)
  xhr.setRequestHeader('Content-Type', 'application/json')
  xhr.onreadystatechange = () => {
    if (xhr.readyState === 4) {
      handleResponse(xhr.response)
    }
  }
  xhr.send(JSON.stringify({ name: 'hello' }))
}