Category: Question and Answers
Updated

This solution is summarized from an archived support forum post. This information may have changed. If you notice an error, please let us know in Discord.

How to Add Row/Delete Seleted Row with Javascript

Issue

I have a table in my page and need to add a new row when "add" is clicked, delete selected row when "delete" is clicked, and submit table data to a backend api when "submit" is clicked. However, my current javascript code is not working and I need help as I am new to appsmith.

Resolution

The issue with the provided code is that the addRow() and delRow() functions are not properly updating the table. Instead of directly manipulating the tableData array, it's recommended to use the setTableData() function provided by the Table1 component. This ensures the table data is updated correctly and the UI refreshes accordingly.

Below is an example of how you can add, delete, and submit data using JavaScript in Appsmith:

export default {
  // Function to add a new row to the table
  addRow: () => {
    const newRow = {
      username: "New User",
      name: "New Name",
      email: "new@email.com",
    };

    // Add the new row to the table data
    const updatedData = [...Table1.tableData, newRow];
    Table1.setTableData(updatedData);
  },

  // Function to delete the selected row from the table
  delRow: () => {
    const updatedData = [...Table1.tableData];
    
    // Remove the selected row using its index
    updatedData.splice(Table1.selectedRowIndex, 1);
    
    // Update the table data
    Table1.setTableData(updatedData);
  },

  // Function to submit the current table data to a backend API
  submitData: () => {
    const data = Table1.tableData;

    // Make an API request to submit data (use fetch, axios, etc.)
    // Example: fetch("your_api_endpoint", { method: "POST", body: JSON.stringify(data) });
  }
};
  • addRow() adds a new row to the existing table.
  • delRow() deletes the selected row based on its index.
  • submitData() sends the current table data to an API.