Aiden Jung
Aiden Jung

Reputation: 11

i can fetch data from google map api but I can't update state with the data

I'm trying to get geo code from google api, save it in state, pass it to GoogleMap component. I get the geo code as an object correctly(like {lat: 37.5397407, lng: 126.9895666}) However, the state is not updated nor "console.log(this.state)" is excuted. Did I do something wrong?

import React from "react";
import PeopleInfoStyle from "../../../styles/presentational/PeopleInfoStyle";
import Carousel from "../../containers/Carousel/Carousel";
import GoogleMap from "../../presentational/GoogleMap/GoogleMap";

class PeopleInfo extends React.Component {
  state = {};

  componentDidMount() {
    let geoData = {};
    fetch(
      `https://maps.googleapis.com/maps/api/geocode/json?address=${
        this.props.person.address
      }&key="SECRET_KEY`
    )
      .then(res => res.json())
      .then(data => {
        geoData = data.results[0].geometry.location;
        console.log(geoData); // {lat: 37.5397407, lng: 126.9895666}
      })
      .catch(err => console.log(err));
    this.setState({ geoLocation: geoData }, ()=>{console.log(state)});
  }
  render() {
    const person = this.props.person;
    const images = [
      <img key={0} alt="" src={person.imgURL} />,
      ...person.subImgURLs.map((url, index) => {
        return <img alt="" src={url} key={index + 1} />;
      })
    ];

    return (
      <PeopleInfoStyle>
        <Carousel>{images}</Carousel>
            {!this.state.getLocation ? null : (
                <GoogleMap
                  id="map"
                  option={{
                    center: {
                      lat: this.state.geoLocation.lat,
                      lng: this.state.geoLocation.lng
                    },
                    zoom: 8
                  }}
                  onMapLoad={map => {
                    const market = new window.google.maps.Marker({
                      position: {
                        lat: this.state.geoLocation.lat,
                        lng: this.state.geoLocation.lng
                      },
                      map: map,
                      title: "business"
                    });
                  }}
                />
        </PeopleInfoStyle>
    );
  }
}

export default PeopleInfo;

Upvotes: 0

Views: 762

Answers (1)

H S
H S

Reputation: 735

The short answer is - the state is not updated with the response of the fetch request.

The state has to be updated once the api-request is completed, i.e. inside one of the "then" callback.

As in the source code above, the setState is called outside the promise (in componentDidMount method ), the promise being asynchronous in nature will not complete as soon as you make a call and then triggering the promise, the interpreter would proceed to call the setState with geodata={}.

I hope you understood, now, the utility of .then(()=>{}). Those ensure the execution of certain code after the Promise is succeeded.

One more pointer, when you want to access the state use this.state, since it is instance property and this is used to access those properties inside the class.

So, the correct setState call, with a callback should look like this - this.setState({geolocation: geodata}, ()=>{console.log(this.state)}).

I hope this helps.

Upvotes: 1

Related Questions