React function dose not reassign (let) or push in array

Viewed 177

Hallo React and Js programmer, I have a question related to function's scoop or variable

I have this code here to get the Postion from gecoder

getPosition = pos => {
    let address;
    Geocoder.reverseGeocode(pos.latitude, pos.longitude, (err, geoData) => {
        if (!err) {
            const data = (geoData.results[0].formatted_address);
            address = data;
        }
    }, apiKey);
    console.log(address);// undefined
}

and I tried to use an array and push the result inside it

const address = [];
Geocoder.reverseGeocode(pos.latitude, pos.longitude, (err, geoData) => {
    if (!err) {
        const data = (geoData.results[0].formatted_address);
        address.push(data);
    }
}, apiKey);
console.log(address[0]);

is there any way to get the value from the data which is a string ? thanks

2 Answers

You're logging variables before they get defined/modified by the callbacks, thus the unexpected results.

This should work:

getPosition = pos => {
  let address;
  Geocoder.reverseGeocode(pos.latitude, pos.longitude, (err, geoData) => {
    if (!err) {
      const data = (geoData.results[0].formatted_address);
      address = data;
    }

    // log INSIDE the callback!
    console.log(address);

  }, apiKey);
}

This too:

// callback is not executed yet, don't log!

const address = [];
Geocoder.reverseGeocode(pos.latitude, pos.longitude, (err, geoData) => {
  if (!err) {
    const data = (geoData.results[0].formatted_address);
    address.push(data);
  }

  // logs INSIDE the callback!
  console.log(address[0]);

}, apiKey);

// callback is not executed yet, don't log!

If you are using getPosition method inside react class component then you can create a state address and store data inside it as following

import React from 'react';

export default class GetPosition extends React.Component {

    state = {
        address: []
    }

    getPosition = pos => {
        Geocoder.reverseGeocode(pos.latitude, pos.longitude, (err, geoData) => {
            if (!err) {
                const data = (geoData.results[0].formatted_address);
                this.setState({address: [...this.state.address, data]})
            }
        }, apiKey);
    }

    render() {
        const address = this.state
        console.log(address)

        return (
            <div>{address[0]}</div>
        );
    }
}

And if it is not a method of react class component you can store data in global address array as following

const address = [];

getPosition = pos => {
    Geocoder.reverseGeocode(pos.latitude, pos.longitude, (err, geoData) => {
        if (!err) {
            const data = (geoData.results[0].formatted_address);
            address.push(data);
       }
    }, apiKey);
}

console.log(address[0]);

I hope this will help you, and you should learn this Understanding Scope in Javascript

Related