I'm trying to update a state. I have been reading that in order not to replace the state altogether, the spread operator needs to be used. It kinds of work as it appends to the previous state but I'm struggling in appending the state in the right place. The code below updates the state for 'categories' but it does it on the same level as 'all_categories' and 'current_category'. I'd like the fetched object to be put inside 'all_categories'. Thank you.
const [ categories, setCategory ] = useState({
all_categories: [],
current_category: 'Cocktail'
});
const [recipes, setRecipe] = useState([]);
useEffect(() => {
Promise.all(
[
fetch(`https://the-cocktail-db.p.rapidapi.com/filter.php?c=${categories['current_category']}`, {
"method": "GET",
"headers": {
"x-rapidapi-host": "the-cocktail-db.p.rapidapi.com",
"x-rapidapi-key": "xxx"
}
}),
fetch("https://the-cocktail-db.p.rapidapi.com/list.php?c=list", {
"method": "GET",
"headers": {
"x-rapidapi-host": "the-cocktail-db.p.rapidapi.com",
"x-rapidapi-key": "xxx"
}
})
]
)
.then(([response1, response2]) => {
return Promise.all([response1.json(), response2.json()])
})
.then(([drinks_data, categories_data]) => {
setRecipe(drinks_data['drinks'])
setCategory(prev_state => {
return {...prev_state, ...categories_data['drinks']};
});
})
.catch(err => { console.log(err); });
},[]);