I've got the following state:
const [places, setPlaces] = useState(false)
const [selectedPlaces, setSelectedPlaces] = useState([])
I asynchronously populate places by calling an API that returns an array of objects that looks something like:
[
{name: "Shop #1", id: 1},
{name: "Shop #2", id: 2}
]
My goal is to render these objects, and have their ID to be added/removed from the selectedPlaces state.
Render:
return (
<div>
<div>
You have selected {selectedPlaces.length} total places
</div>
(places === false)
? <div>Loading...</div>
: places.map(place => { // render places from the places state when loaded
let [name, id] = [place.name, place.id]
return <div onClick={() => {
setSelectedPlaces(selected => {
selected.push("dummy data to simplify")
return selected
})
}}>{name}</div>
})
</div>
)
I've removed the key and added dummy data to make the movements simpler.
The problem arises when clicking on a div, the "You have selected ... total places" doesn't refresh until I force a re-render using fast refresh or through other methods (using browser/NextJS). Is this correct behaviour? It's as-if the state isn't being changed, but a
console.log
on thesetSelectedPlaces
displays fresh data symbolizing it is being changed.
I've tried:
- Creating a
useEffect
handler for theselectedPlaces
state which wouldsetAmtPlaces
using the length of the selected places. The same issue arises. - Searched/read-through multiple posts/GitHub issues like this and this
- Replacing the list state with true/false in previous times I've encountered this issue, but I cannot use that approach with this problem since it's a dynamic amount of data being loaded.