Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-google-maps map not updated when passed props and the marker is one location behind when updated

I have the map working when it loads, but whenever I pass props the map itself never changes.

The marker changes, but is always 1 state behind what it should be, obviously a sync issue but I'm not sure how to fix this in my component.

class Map extends React.Component {
  state = {
     center: { lat: 50.937531, lng: 6.960278600000038 }
  }

  componentWillReceiveProps = () => {
    this.setState({
      center: { 
        lat: Number(parseFloat(this.props.city.lat)),
        lng: Number(parseFloat(this.props.city.lng))
      }
    });
  }

  render() {
    console.log(this.state.center)
    return (
      <div>
        <MapDetails
          googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyB-L-IikkM6BZ_3Z2QIzbkx4pdAkP76tok&v=3.exp&libraries=geometry,drawing,places"
          loadingElement={<div style={{ height: `100%` }} />}
          containerElement={<div style={{ height: `100vh`}} />}
          mapElement={<div style={{ height: `100%` }} />}
          mapCenter={this.state.center}
        />
      </div>
    )
  }
}

const mapStateToProps = (state) => {
  return { city: state.CityNameReducer }
}

export default connect(mapStateToProps)(Map);

const MapDetails = withScriptjs(withGoogleMap(props =>
  <GoogleMap
    defaultZoom={12}
    defaultCenter={props.mapCenter}
  >
    <Marker
      position={props.mapCenter}
    />
  </GoogleMap>
));

The biggest question I have is why the map itself is not updating?

like image 897
Matt Brody Avatar asked Apr 11 '19 01:04

Matt Brody


People also ask

Can I use map on state in React?

A map is not the feature of React. Instead, it is the standard JavaScript function that could be called on any array. The map() method creates a new array by calling a provided function on every element in the calling array.


1 Answers

Add a key to GoogleMap component. a Key should be unique each time provided. for your testing use new Date().getTime() function.

<GoogleMap key={new Date().getTime()}/>

as I mentioned its for only testing so make sure to provide this key in better way

like image 116
Sajed Avatar answered Nov 15 '22 08:11

Sajed