Blog>
Snippets

Reactivity with Asynchronous Operations

Handle asynchronous operations such as fetching data from an API and showing how the state updates reactively on data arrival.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reactivity with Async Operations</title>
<style>
  #data-container {
    padding: 10px;
    border: 1px solid #000;
    margin-top: 20px;
  }
</style>
</head>
<body>

<div id="app">
  <button id="fetch-button">Fetch Data</button>
  <div id="data-container">Data will appear here after fetching.</div>
</div>

<script>
// Reactivity setup
const appState = {
  data: null,
  setData(newData) {
    this.data = newData;
    document.getElementById('data-container').textContent = JSON.stringify(newData, null, 2);
  }
};

// Asynchronous operation - Fetching data from an API
async function fetchData() {
  const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  const data = await response.json();
  appState.setData(data);
}

document.getElementById('fetch-button').addEventListener('click', fetchData);
</script>

</body>
</html>
This HTML file contains an example of reactivity with asynchronous operations. There is a button that, when clicked, triggers a fetch operation from a placeholder API. Once the data is fetched, the state is updated reactively, and the new data is displayed within a div element. The CSS styles are minimal, simply adding a border and padding around the container where the data will be displayed. JavaScript is used to define the reactive appState, handle the fetch operation, and update the DOM reactively when new data is available.