0

Im trying to store multiple values in an array by giving a set of predefined data. The select options are clickable components. I have 2 arrays, one is for store values, and another one is for selected values.

const [selected, setSelected] = useState<string[]>([]);
const [categories] = useState<string[]>([
  "fashion", "sports", "gaming", "lifestyles", "finance"
])

I have custom components for display components. When I click them the selected state not updating but after code change/save the codes again in the editor the components get rendered correctly. Anyone have any idea about it. Thanks in advance

const handlePress = (e) => {
    let temp = selectedValues || [];
    const val = temp?.findIndex(a => a === e);
    if (!temp || val === -1) {
      temp.push(e);
    } else {
      temp.splice(val, 1);
    }
    setSelectedValues(temp);
  }

  return (
    <>
      {categoryList.map(e => {
        return <CategoryItem
          key={e}
          text={e}
          selected={selectedValues.includes(e)}
          style={{ height: 28 }}
          handlePress={handlePress} />
      })}
    </>
  )

category-item.tsx

<TouchableOpacity style={selected ? viewStyleSelected : viewStyle} onPress={() => handlePress(text)}>
  {content}
</TouchableOpacity >
Suhail Moh
  • 45
  • 1
  • 1
  • 11
  • 2
    assuming `selectedValues` is state, you should be making a copy of it: `let temp = [...selectedValues];` and default your state to an empty array `[]` in `useState()`, otherwise you're modifying your state inplace – Nick Parsons Aug 16 '21 at 12:02

1 Answers1

2

You are mutating the state variable. Therefore, react thinks it is the same object, and doesn't re-render. You need to set a new array to selectedValues:

const handlePress = (e) => {
  setSelectedValues(selectedVals => {
    return selectedVals.includes(e) ? [...selectedVals, e] :
    selectedVals.filter(val => val !== e)
  })
}
Sinan Yaman
  • 5,714
  • 2
  • 15
  • 35