Blog>
Snippets

Handling multiple concurrent optimistic updates

Illustrate a strategy for managing and synchronizing multiple concurrent optimistic updates in a component, ensuring that the user interface reflects a consistent and up-to-date state.
let optimisticUpdates = [];

function addOptimisticUpdate(update) {
  optimisticUpdates.push(update);
}
Define a global array to track optimistic updates and a function to add updates to this array.
function rollbackOptimisticUpdate(id) {
  optimisticUpdates = optimisticUpdates.filter(update => update.id !== id);
}
Function to roll back an optimistic update by ID, removing the update from the tracking array.
function applyOptimisticUpdate(data) {
  // Assume data is an object representing the new state
  optimisticUpdates.forEach(update => {
    // Apply each optimistic update to the data
    data = update.applyUpdate(data);
  });
  return data;
}
Function to apply all tracked optimistic updates to the current state of data, ensuring the UI reflects these changes.
function handleMultipleConcurrentUpdates(updates) {
  updates.forEach(update => {
    // Apply optimistic update immediately to UI
    let tempData = applyOptimisticUpdate(update.data);
    // Update UI with tempData
    // Simulate sending update to server
    simulateServerRequest(update)
      .then(response => {
        // Success, remove optimistic update from tracking
        rollbackOptimisticUpdate(update.id);
      })
      .catch(error => {
        // Rollback optimistic update if error
        rollbackOptimisticUpdate(update.id);
        // Optionally, restore UI to previous state
      });
  });
}
Function to handle and synchronize multiple concurrent optimistic updates. Applies each update to the UI, sends the update to the server, and rolls back if necessary.
function simulateServerRequest(update) {
  return new Promise((resolve, reject) => {
    // Simulate network request
    setTimeout(() => {
      if (Math.random() > 0.5) {
        resolve('Success');
      } else {
        reject('Error');
      }
    }, 1000);
  });
}
Simulates a server request with a 50% chance of success or failure. Used to demonstrate handling of updates.