Search code examples
javascriptreactjsapigoogle-mapses6-promise

Issue in mapping through array in reactjs


I am new to ReactJs. My Project is fetching data from my backend, which contains a Cell Id, and then sending that Cell Id to another api and receiving the latitude and longitude of the Cell ID. In order to do this I have to store the locations for each cell Id. It seems that I am able to store the latitude and longitude in this.state.loc. However I am running into an issue when mapping through that array to put markers on the map. In the first code block when I try to log the latitude of the locations to the console it only logs one of them.


import React, {Component,useState, useEffect} from 'react';
import './App.css';
import {GoogleMap, withScriptjs, withGoogleMap, Marker, useLoadScript, InfoWindow} from "react-google-maps";







class App extends Component {
  
    constructor(props) {
        super(props);
        this.state = {
        users: [],
        loc:[{}]
        
            
        };
    }
    

  
    
  
    
   componentDidMount() {
    
        fetch('/users')
        .then(res=>res.json())
        .then(users=>this.setState({users}))
        .then(users=>this.state.users.map(user => {
                 
                                              
                                
            var num = user.CallingCellID
            if(num != null) {
                                                                                  
                                                                                  
                                var digits = (num).toString().split('');
                                var realDigits = digits.map(Number);
                                var mcc = 419;
                                var mnc = 4;
                                                                                  
                                var lac = (realDigits[6]*1000) + (realDigits[7]*100) + (realDigits[8]*10) + (realDigits[9]*1);
                                var cid = (realDigits[10]*10000)+ (realDigits[11]*1000) + (realDigits[12]*100) + (realDigits[13]*10) + (realDigits[14]*1);
                                fetch("https://api.mylnikov.org/geolocation/cell?v=1.1&data=open&mcc=419&mnc=4&lac="+lac+"&cellid="+cid)
                                .then(response => response.json())
                                .then(result=> {
                                const locations = result.data;
                                      
                                if(locations.lat != undefined) {
                                      
                                var x = [{lat: locations.lat, lng: locations.lon}];
                                      
                                Promise.all(x).then(data => {this.setState({ loc: data })})
                                      
                                }
                                                                                        
                                                                                        
                                });
                                                                                  
                                                                                  
                                                                                  
                }
          }));
    }
    
                                              

    
    
    
  
    
    
    render() {

        const MyMapComponent = withScriptjs(withGoogleMap((Map) =>
                            <GoogleMap defaultZoom={2} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
                                   {this.state.loc.map(l=>console.log(l.lat))}                     
                                                          
                                </GoogleMap>))

 
        

    return (
            
            <div className="App">
            <header className="App-header">
            <form>
            <label for="Location Search"> Location Search: </label>
            <input type = "text" id = "Location Search" name = "Location Search"/>
            
            <label for="Account Search"> Account Search: </label>
            <input type = "text" id = "Account Search" name = "Account Search"/>
            <label for="IMSI Search"> IMSI Search: </label>
            
            <select id="IMSI Search" name="IMSI">

           <option value="1">1</option>)
            </select>
            
            <label for="IMSI RANGE:"> IMSI RANGE </label>
        
            <input type = "text" id = "IMSI RANGE" name = "IMSI RANGE"/>
            <input type = "text" id = "IMSI RANGE2" name = "IMSI RANGE2"/>
            
            
            </form>
            
            <div id = "googlemap">
            
            <MyMapComponent
            isMarkerShown
            googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyCa3cfZfuFgpKPUWpXZv7WejZ7u_093A3s"
            loadingElement={<div style={{ height: `800px` }} />}
            containerElement={<div style={{ height: `1500px` }} />}
            mapElement={<div style={{ height: `800px` }} />}
            />
       
          
            
            </div>
            
           
            
          
            
            
            
            
            </header>
            </div>
            
            );
    
    }
    
}

export default App;



But in the code block below, when I move the map function for loc outside myMapComponent, and just below render(), it successfully logs the latitudes to the console.

 render() {
{this.state.loc.map(l=>console.log(l.lat))}   
        const MyMapComponent = withScriptjs(withGoogleMap((Map) =>
                            <GoogleMap defaultZoom={2} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
                                                     
                                                          
                                </GoogleMap>))

I am new to react, so I am not sure what is the issue. Im not sure if it has to do with the way I stored the locations for each Cell ID, or if it's some other issue.


Solution

  • You will have to use a callback function because after calling setState , the data might not be updated immediately for use.

    You will need to pass a callback function like this

    this.setState({users}, () => {
    **Do your this.state.users.map **
    })
    

    You can refer to this post also.

    When to use React setState callback