-2

I have a basic React Maps POC that shows Pins of users on the map, I use React Hooks to set those users and locations on load and everything works well, when I inject a new user Inject User button to the state and then do a fitBounds, the map updates with the new user and fits the bounds with that new user.

When I click on the Fetch Users button I update the state to the initial set of users and I do a fitBounds, the last user then gets removed from the map and the state but the bounds aren't updated. Only when I click on Fetch Users for the second time then only does fitBounds work.

Link to my repository: https://github.com/ArrieAgilite/react-maps-poc.git

1 Answers1

0

All forms of setters, that change the state are async. This means they actually run after your method using them finishes.

You are setting state in getMyPlaces(). So the fitBounds inside the onClick of the button

onClick={() => {
   getMyPlaces();
   fitBounds(mapRef)
}}

runs BEFORE the state is actually set.

You should add an effect, that triggers the fitBounds after changes to the places, like this:

useEffect(() => {
  fitBounds();
}, [places])
colburton
  • 4,685
  • 2
  • 26
  • 39