Natasha Kelly
Natasha Kelly

Reputation: 73

React: Google Places API/ Places Details

I have the following code which retrieves Google Places Reviews based on Google Places API. I have incorporated the logic to work as a React life cycle component. Currently, I am unable to setState and correctly bind the object. I could use some help understanding where my logic is failing.

export default class Reviews extends React.Component{
constructor(props){
    super(props);
    this.state = {
      places: []
    }
  }


componentDidMount(){


let map = new google.maps.Map(document.getElementById("map"), {
    center: {lat:40.7575285, lng: -73.9884469}
  });

  let service = new google.maps.places.PlacesService(map);

service.getDetails({
    placeId: 'ChIJAUKRDWz2wokRxngAavG2TD8'
  }, function(place, status) {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
      console.log(place.reviews);
      // Intended behavior is to set this.setState({places.place.reviews})
    }
  })
}
render(){
const { places } = this.state;
return(
  <div>
    <p>
      {
        places.map((place) => {
          return <p>{place.author_name}{place.rating}{place.text}</p>
        })
      }
    </p>
  </div>
  )
 }
}

Upvotes: 1

Views: 4764

Answers (2)

Natasha Kelly
Natasha Kelly

Reputation: 73

With some tweaking -- I got the code to work! Thank you.

render(){
const { places } = this.state;
return(
  <div>
    <p>
      {
        places.map((place) => {
          if(place.rating >= 4){
            return <p key={place.author_name}>{place.author_name}{place.rating}{place.text}</p>
          }
        })
      }
    </p>
  </div>
 )
}

Upvotes: 1

Mark
Mark

Reputation: 92440

You can't use this that way in a callback. When the function is called the this in, this.setState({places.place.reviews}) doesn't point to your object. One solution is to use => function notation which will bind this lexically.

service.getDetails({
    placeId: 'ChIJAUKRDWz2wokRxngAavG2TD8'
}, (place, status) => {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
      console.log(place.reviews);
      this.setState({places: place.reviews})
    }
  })
}

Alternatively you can make a new reference to this and us it in the function. Something like

var that = this
...
that({places.place.reviews})

The first option is nicer, but requires an environment where you can use ES6. Since your using let you probably are okay.

Upvotes: 1

Related Questions