I have filterData
which comes from a controller, so i set filterData
to options, for the UI,Like this
const [state, setState] = React.useState({ options: filterData, });
filter data is this
[{"List": [{"Name": "TEST1", "isSelected": false}, {"Name": "TEST2", "isSelected": false}, {"Name": "TEST3", "isSelected": true}], "Type": "Type"},{"List": [{"Name": "TEST4", "isSelected": false}, {"Name": "TEST5", "isSelected": false}, {"Name": "TEST6", "isSelected": true}], "Type": "Type2"}]
I render it in a flatlist
and then map
the List, this is the code for my flatlist
<FlatList style={{flex: 1, backgroundColor: colors.white}} data={state.options} keyExtractor={(_, index) => index.toString()} renderItem={({item, index}) => { return (<View style={{marginBottom: widthPercentageToDP(5)}}><Text> {item.Type}</Text><View style={{ flexDirection: 'row', flexWrap: 'wrap', }}><View style={{ marginRight: 8, marginBottom: 8, }}><TouchableOpacity><Text> Select All</Text></TouchableOpacity></View> {item.List.map((e: any, idx: number) => (<View key={idx}><TouchableOpacity onPress={() => handleSelect(idx, item.Type) }><Text> {e.Name}</Text></TouchableOpacity></View> ))}</View></View> ); }}</View></View> ); }} />
as you can see from above, i will have some buttons
. And if the button
is clicked, it will call handleSelect
function. which is this
const handleSelect = async (idx: number, type: string) => { let arr = [...state.options]; arr.map((item) => { if (item.Type === type) { item.List[idx].isSelected = !item.List[idx].isSelected; } }); console.log(state.options) };
i didnt change the state of the options like the code below, only console.log
setState((prevState) => ({ ...prevState, options: arr, }));
The problem is, in the log when i clicked and run that function, state.options
will also change.it will have the same data as arr
. Even filterData
also change when i console.log
in handleselect
. I already checked my controller and it didnt trigger any function.Does anyone know why it update all of my variable?