I have a state in my app which is something like following:
const [companyCategories, setCompanyCategories] = useState({ loading: true, categories: null });
I fetch my categories from an API and set my categories like below:
const fetchCategories = useCallback(() => {
fetch(***link***)
.then(res => {
if (!res.ok) {
throw new Error('Failed to fetch.');
}
return res.json()
})
.then(data => {
setCompanyCategories({
loading: false, categories: data.map((el, index) => {
return {
id: el.id,
title: el.title,
selected: false
}
})
})
})
.catch(err => {
console.log(err);
});
}, []);
and if I log my companyCategories after that:
Object {
"categories": Array [
Object {
"id": 7,
"selected": false,
"title": "Casual",
},
Object {
"id": 8,
"selected": false,
"title": "Coffe Table",
},
Object {
"id": 10,
"selected": false,
"title": "Dining Table",
},
Object {
"id": 11,
"selected": false,
"title": "Workstation",
},
],
"loading": false,
}
and here's my problem : consider I show this categories as buttons to UI of the app and when user tap on each it changes by the color and I need to alter selected attribute of the category to true which by default all of them are false means that none selected.
for this I code like this:
const onRadioBtnClick = (item) => {
let updatedState = companyCategories.categories.map((el) => {
if (el.id == item.id) {
return {
...el,
loading: true,
categories: {
...el.categories,
selected: !el.selected
}
}
}
setCompanyCategories(updatedState)
});
};
and this doesn't work, updatedState is showing me undefined. how can I manipulate one property of my nested state?