when using Flatlist / map in react /react native then the item’s component state is not updated correctly
Problem :-
parent component
`<FlatList
data={itemList}
renderItem={({ item }) => (
<Item
item={item}
/>
)}
keyExtractor={(item, index) => item.id}
keyExtractor={(item, index) => String(index)}
/>`
**Item component(Child):-
**
`import React, { useState } from ‘react’;
import { Checkbox } from ‘native-base’;
function Item({ item }) {
const [isChecked, setIsChecked] = useState(item.status === 1); // <<< — at the time of rendering Item component isChecked value is not updated correctly
const toggleCheckbox = () => {
setIsChecked(!isChecked);
};
return (
<Checkbox
alignSelf={'flex-start'}
mt={1}
size="md"
value={item.name}
accessibilityLabel="Task checkbox"
isChecked={isChecked} // <<-- state value is not updating that's why it's not checked / uncheck the checkbox when item card is populated
isDisabled={isChecked} // <<-- same here
onChange={toggleCheckbox}
/>
);
}
export default Item;`
Solution :-
just replace the keyExtractor inside parent component’s FlatList with uniqe key name like (id / name)
keyExtractor={(item, index) => String(index)}
to this
keyExtractor={(item, index) => item.id}
`<FlatList
data={itemList}
renderItem={({ item }) => (
<Item
item={item}
/>
)}
keyExtractor={(item, index) => item.id} //<<<---- Here not use **index** insted use **id**
/>`