Following code works fine the first time, It finds the correct item and changes its checked value, but if I call the same function with the same id again it returns undefined. any idea why?
This code is using in a React Native Application where the checkbox is updated using this method
CheckBox :
<CheckBox value={item.checked} key={item.id} onValueChange={setSelection} onChange={()=> {
handleChange(item.id);
}}
style={styles.checkbox}
tintColors={{ true: "#ffc324", false: "#ffc324" }}
/>
const handleChange = (id) => {
const ids = id;
let changedCheckbox = categories.find((category) => {
return category.subcategory.find((item) => {
if (item.id === ids) {
return (item.checked = !item.checked);
}
});
});
console.log(changedCheckbox);
};
This is the JSON I use
[
{
"id": 1,
"name": "MOTs",
"filename": "1610270182.png",
"bg_filename": null,
"content": "You can try this set a state like this and check if your component mounted or not. This way you are sure that if your component is unmounted you are not trying to fetch something.",
"featured": 1,
"created_at": "2021-01-10T09:16:22.000000Z",
"updated_at": "2021-01-10T09:40:37.000000Z",
"subcategory": [
{
"id": 1,
"name": "MOT1",
"category_id": 1,
"image_name": null,
"created_at": null,
"updated_at": null,
"checked": false
},
{
"id": 2,
"name": "MOT2",
"category_id": 1,
"image_name": null,
"created_at": null,
"updated_at": null,
"checked": false
},
{
"id": 3,
"name": "MOT3",
"category_id": 1,
"image_name": "1611678308.png",
"created_at": "2021-01-26T16:25:11.000000Z",
"updated_at": "2021-01-26T16:31:24.000000Z",
"checked": false
}
]
}
]
Advertisement
Answer
const handleChange = (id) => {
const category = categories.find(category => {
const item = category.subcategory.find(item => item.id === id);
if (item) item.checked = ! item.checked;
return !!item;
});
console.log(category)
};
Toggle checked then return boolean not checked.