question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to remember selected rows if outside state changes with indexes rather than identifiers

See original GitHub issue

Hey there,

first of all, thanks for your efforts on this library 🚀

Today I ran into the following limitation when using MUI Datatables: Pairing selectableRows with outside state changes. In my case, I want to enable row selection. That’s built-in into MUI Datatables, so I just activate it with the option selectableRows.

Problem: However, now I experience outside state changes, such as from a search feature (but many more other features, just keeping it only search for the sake of keeping the example simple).

A minimal scenario is shown in this CodeSandbox: https://codesandbox.io/s/muidatatables-no-state-yhc2d

For the sake of completeness, here the code again:

import React from "react";
import ReactDOM from "react-dom";
import MUIDataTable from "mui-datatables";

let data = [
  { id: "42", name: "Person 42" },
  { id: "43", name: "Person 43" },
  { id: "44", name: "Person 44" },
  { id: "45", name: "Person 45" },
  { id: "46", name: "Person 46" },
  { id: "47", name: "Person 47" },
  { id: "48", name: "Person 48" },
  { id: "49", name: "Person 49" },
  { id: "50", name: "Person 50" },
  { id: "51", name: "Person 51" }
];

const App = () => {
  const [search, setSearch] = React.useState("");
  // const [selectedRowIds, setSelectedRowIds] = React.useState([]);

  const columns = [
    {
      name: "id",
      options: {
        display: false
      }
    },
    {
      label: "Name",
      name: "name",
      hidden: true
    }
  ];

  // const onRowSelectionChange = (
  //   currentRowsSelected,
  //   allRowsSelected,
  //   rowsSelected
  // ) => {
  //   const filteredData = search
  //     ? data.filter((item) =>
  //         item.name.toLowerCase().includes(search.toLowerCase())
  //       )
  //     : data;

  //   const ids = rowsSelected.map((index) => filteredData[index].id);

  //   setSelectedRowIds(ids);
  // };

  const filteredData = search
    ? data.filter((item) =>
        item.name.toLowerCase().includes(search.toLowerCase())
      )
    : data;

  const options = {
    // onRowSelectionChange,
    selectableRows: true,
    // rowsSelected: selectedRowIds.map((id) =>
    //   filteredData.findIndex((item) => item.id === id)
    // ),
    download: false,
    print: false,
    filter: false,
    search: false,
    viewColumns: false,
    pagination: false
  };

  return (
    <React.Fragment>
      <label>
        Filter by Name:
        <input
          type="text"
          onChange={(event) => setSearch(event.target.value)}
        />
      </label>

      <MUIDataTable data={filteredData} columns={columns} options={options} />
    </React.Fragment>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));

So if I select for Person 43 and search for 5, then I get Person 50 selected. If I remove the search, Person 43 is selected again. This is because MUI Datatables uses indexes rather than identifiers.

Now, with this implementation detail in mind, am I supposed to keep track of the selected indexes while search (and many other filters etc. from the outside) is(/are) applied on my data? That’s what I am doing in the commented lines of code and it works. However, I wouldn’t expect to have this much of a workaround to get it working. In the end, I would assume that I would be able to pass in a list of identifiers rather than indexes which are not in fixed order/size/etc.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
rwieruchcommented, Oct 28, 2020

I am just wondering why one has to jump through these hoops. If it would be just possible to rely on identifiers rather than on indexes (which change all the time) 😅 Feel free to close this issue if there is no other way around it.

0reactions
notimetoanalysecommented, Aug 30, 2021

Is there any update on this issue? I totally love your lib! but it’s very inconvenient to write some workarounds for such a seemingly simple feature. Faced the same issue in my project, where searching would break the selection flow - indexes refer to initial data, not the one that is shown after search. Exposing some row data in the onRowSelectionChange would be much appreciated

p.s. nevermind, I should’ve used dataIndex instead of the index

Read more comments on GitHub >

github_iconTop Results From Across the Web

Handling row selection in a table view - Apple Developer
Managing an exclusive list is similar. Deselect the row and display a checkmark or an accessory view to indicate the selected state. But...
Read more >
Index-Match-Match: How to Index-Match Rows and Columns
Step 3: Tell Excel where you want to search​​ Remember that the state list maps states names to their abbreviations. It's like the...
Read more >
Indexing, Slicing and Subsetting DataFrames in Python
Manipulate and extract data using column headings and index locations. Employ slicing to select sets of data from a DataFrame.
Read more >
Top 10 questions and answers about SQL Server Indexes
To keep track of those pages, SQL Server uses a special set of pages, ... index, the order of the rows in the...
Read more >
Excel INDEX function with formula examples - Ablebits
The INDEX array form returns the value of a certain element in a range or ... Instead of entering the row and column...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found