Completely Replacing a Table in Grist

Hello everyone,

For one of our usecase, we’re considering integrating a custom widget that would execute an SQL query each time one of the reference tables is updated, and would then generate an aggregated table and then replace our aggregated table with the new result.

But I can’t manage to replace the aggregated table with its updated version.

Basically, for our tests within the custom widget, we’ve defined the following:

document.addEventListener('DOMContentLoaded', function() {
  grist.ready();

  document.getElementById('executeButton').addEventListener('click', async function() {
    // Define the data
    const predefinedData = [
      { id: 1, CTM: "Lyon Centre", nombre: 42 },
      { id: 2, CTM: "Villeurbanne", nombre: 35 },
      { id: 3, CTM: "Vaulx-en-Velin", nombre: 28 },
      { id: 4, CTM: "Bron", nombre: 19 },
      { id: 5, CTM: "Vénissieux", nombre: 31 }
    ];
    
    // Convert the data to BulkColValues format
    const bulkData = convertToBulkColValues(predefinedData);
    
    // Replace using applyUserAction: ReplaceTableData
    // Documentation: export type ReplaceTableData = ['ReplaceTableData', string, number[], BulkColValues];
    await grist.docApi.applyUserActions([
      ['ReplaceTableData', 'TestiTesta', [], bulkData]
    ]);
  });
});

function convertToBulkColValues(records) {
  if (records.length === 0) {
    throw new Error("Aucune donnée à insérer.");
  }

  const columns = Object.keys(records[0]);

  let bulkColValues = {};
  columns.forEach(col => {
    bulkColValues[col] = records.map(row => row[col] ?? null);
  });
  return bulkColValues;
}

And the corresponding HTML for testing:

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Grist Button</title>
</head>
<body>
    <button id="executeButton">Exécuter</button>
</body>
</html>

I based this on a DocAPI: Update records set with an option to replace the whole table · Issue #626 · gristlabs/grist-core · GitHub which seemed to indicate that ReplaceTableData works even though it’s not fully documented:

However, I end up with the following error:

> **PLUGIN VIEW /grist-widget/custom-widget-builder/index.html: Rpc for ?: RPC_UNKNOWN_REQID Response to unknown reqId 1**

Could you shed some light on a working way to replace a table with another in a functional way? Did i miss something about the ReplaceDataTable Method ?

Thanks in advance!