Skip to content

SelectPanel should compare Objects based on key or id instead of the Objects themselves #4315

Description

@ajhenry

Description

When passing in objects to the SelectPanel component, the selected items may not render correctly since they are doing direct object comparison:

onAction: (itemFromAction,event)=>{
item.onAction?.(itemFromAction,event)
if(event.defaultPrevented){
return
}
if(isMultiSelectVariant(selected)){
constotherSelectedItems=selected.filter(selectedItem=>selectedItem!==item)
constnewSelectedItems=selected.includes(item) ? otherSelectedItems : [...otherSelectedItems,item]
constmultiSelectOnChange=onSelectedChangeasSelectPanelMultiSelection['onSelectedChange']
multiSelectOnChange(newSelectedItems)
return
}
// single select
constsingleSelectOnChange=onSelectedChangeasSelectPanelSingleSelection['onSelectedChange']
singleSelectOnChange(item===selected ? undefined : item)
onClose('selection')
},

If the items are defined in the component, they could rerender and create new object references. Then this comparison check will always return false as the original objects are held in useState.

Instead, we should rely on comparing the key or id props as these are guaranteed* to be unique per object.

So our comparison function would instead look something like the following:

onAction: (itemFromAction,event)=>{item.onAction?.(itemFromAction,event)if(event.defaultPrevented){return}if(isMultiSelectVariant(selected)){constotherSelectedItems=selected.filter(selectedItem=>selectedItem.key!==item.key)constnewSelectedItems=selected.find(selectedItem=>selectedItem.key===item.key) ? otherSelectedItems : [...otherSelectedItems,item]constmultiSelectOnChange=onSelectedChangeasSelectPanelMultiSelection['onSelectedChange']multiSelectOnChange(newSelectedItems)return}// single selectconstsingleSelectOnChange=onSelectedChangeasSelectPanelSingleSelection['onSelectedChange']singleSelectOnChange(item.key===selected.key ? undefined : item)onClose('selection')},

cc: @ipc103

Steps to reproduce

Minimal Repo
https://codesandbox.io/p/sandbox/dreamy-cache-msfqyq

Version

v35.26.0

Browser

Chrome

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions