I'm trying to have a food filter page whereby the user presses buttons to indicate their preference so that on confirm, I would be able to have the user's preference stored as on object with keys "area", "cuisine" and "price". After trying various combinations, the logged object I get keeps only reflecting a change in the first update which is area. {"area": "South", "cuisine": Array [], "price": -Infinity } instead of {"area":"South", "cuisine": "Japanese Cuisine", "price": 3}. How do I deal with this async nature of setstate to get all the updates correct? (the handle press functions are passed to children component for area cuisine and price)
Filter.js
const [filters, setFilters] = React.useState({});
React.useEffect(() => {
setFilters({ area: "", cuisine: "", price: 0 });
}, []);
const handleAreaPress = (area) => {
setFilters((prevState) => ({ ...prevState, area: area }));
};
const handleCuisinePress = (cuisine) => {
setFilters((prevState) => ({ ...prevState, cuisine: cuisine }));
};
const handlePricePress = (price) => {
let max = Math.max(...price);
setFilters((prevState) => ({ ...prevState, price: max }));
};
const handleConfirmPress = () => {
console.log(filters); // expected log to be {"area":"South", "cuisine": "Japanese Cuisine", "price": 3}
};
Area.js
const AreaSelection = ({ handleAreaPress }) => {
const [selected, setSelected] = React.useState([]);
const areas = ["North", "South", "East", "West", "Central"];
const handlePress = (area) => {
setSelected(area);
};
const buttons = () =>
areas.map((items) => (
<TouchableOpacity
key={items}
onPress={() => {
handlePress(items);
handleAreaPress(items);
}}
style={[
styles.button,
{
backgroundColor: selected.includes(items)
? "silver"
: "white",
},
]}
>
Cuisine.js
const CuisineSelection = ({ handleCuisinePress }) => {
const [selected, setSelected] = React.useState([]);
const cuisine = [
"Asian",
"Western",
"Chinese",
"Korean",
"Indian",
"Japanese",
"Cafe",
"Local",
];
const handlePress = (cuisine) => {
selected.includes(cuisine)
? setSelected(selected.filter((s) => s !== cuisine))
: setSelected([...selected, cuisine]);
};
const buttons = () =>
cuisine.map((items) => (
<TouchableOpacity
key={items}
onPress={() => {
handlePress(items);
handleCuisinePress(selected);
}}
style={[
styles.button,
{
backgroundColor: selected.includes(items)
? "silver"
: "white",
},
]}
>
