How to re-select a previously selected table row

I have a table with contents that get updated when a user presses a button. Starting off, the first table row should be selected (only one selection is allowed). On subsequent table updates, I would like to preserve the user’s selection, if the row still exists, or revert to the first table row.

I found here that in Observable notebooks this can be done using ‘this’. In the framework how can the previous state of a table input be accessed?

Thanks a lot in advance

I think this question raises two subquestions:

  • what is the equivalent of this in Framework
  • how do you decide that a row in the new selection is the same as the row in the old selection

There might be a better way, but here is a possibility to solve the first issue (contrived example):

```js echo
const items = view(
  Inputs.select(
    new Map([
      ["All penguins", penguins],
      ["Biscoe", penguins.filter((d) => d.island === "Biscoe")],
      ["Female", penguins.filter((d) => d.sex === "FEMALE")]
    ])
  )
);
```

```js echo
const individual = view(
  Inputs.table(items, {value: items.find((d) => d === state.individual) ?? items[0], multiple: false})
);
```

```js echo
const state = {individual: null};
```

```js echo
// Show the selected individual item, and update state
display(Inputs.table([individual]));
state.individual = individual;
```

Now if the items in the array are not the exact same object from one selection to the next, you could fix the second issue by finding another mean to test if they correspond to the same individual (typically, by comparing their id). For example instead of items.find((d) => d === state.individual) we could say:

items.find((d) => d.id === state.individual.id)

Thanks very much for your suggestion!

By reading here that:

only the code block that declares a top-level variable can define it or assign to it

I thought it meant that state.individual = individual in a cell different from the defining one would cause an error. Instead, I tried to apply the mutables pattern but I run into scope problems.

As you said, it would be great if we knew the equivalent of this in Framework.