JSFiddle - React, Tailwind, and code Playground

by webvitaly

HTML

<button class="js-button">
Get random post
</button>

<div class="js-output"></div>

JavaScript

const button = document.querySelector('.js-button');
const output = document.querySelector('.js-output');

async function getRandomPost() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    const posts = await response.json();
    const randomIndex = Math.floor(Math.random() * posts.length);
    const randomPost = posts[randomIndex];
    output.textContent = randomPost.body;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

document.addEventListener("DOMContentLoaded", async function() {
  await getRandomPost();
});

button.addEventListener('click', async function() {
  await getRandomPost();
});