I have a hook for saving state in local storage:
const [expandingState, setExpandingState] = useLocalStorageState<Record<string, boolean>>(
'expandingState',
{},
);
and after user is clicking on expand/collapse element I manipulate state value using setExpandingState like this:
const handleExpandCollapse = (row: UseTableRowProps<TableTreeProps>): void => {
setExpandingState(prevState => {
if (!prevState[row.id]) {
return {
...prevState,
[row.id]: true,
};
} else {
const newState = { ...prevState };
delete newState[row.id];
return newState;
}
});
};
More about particular react-table API: https://react-table.tanstack.com/docs/api/useExpanded
I use row.id to bind the clicked field and expandingState values, but with this approach if we add or remove one more element to the table, then the row.id of each row of the table is shifted and we have incorrect values in the state and, as a result, not correctly display expanded and collapsed table elements...