0

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.

1 Answers1

0

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

Kevin Moe Myint Myat
  • 1,916
  • 1
  • 10
  • 19
  • Hi @KevinMoeMyintMyat ,My code looks like `.then(res=>res.json()) .then(users=>this.setState({users}, () => {**this.state.users.map })`. I forgot to mention this but when my `console.log()` is outside `MyMapComponent`. Each latitude is being logged twice to the console. Im not sure why that is occurring either. – Deyvik Bhan Aug 24 '20 at 03:57
  • @DeyvikBhan Your problem now is the state.loc has only one location instead of multiple ? I think it's because you are setting a state in each iteration. What you need to do is declare an empy array outside before the .map iteration and during the looping, push the results inside. And after all looping, use the setState of that array. Moreover, I prefer .forEach in this situation instead of .map – Kevin Moe Myint Myat Aug 24 '20 at 05:50
  • HI @KevinMoeMyintMyat Thanks for your reply. I implemented it, and when I do console.log(my.state.loc) it returns an object like `[{....}]` and when I click to expand it returns this in the console. `0: {} ,1: [{...}], 2:[{...}]`. Again I am unable to map through it using the mapping method I used in my code above. Is there a different method to map through it, or is the result I am getting in the wrong format? – Deyvik Bhan Aug 24 '20 at 23:44
  • @DeyvikBhan may I get the sample api call and response? I tried https://api.mylnikov.org/geolocation/cell?v=1.1&data=open&mcc=419&mnc=4&lac=0&cellid=0 but got Object was not found error. for lac and cellid value what did you use? – Kevin Moe Myint Myat Aug 25 '20 at 02:16
  • Hi sorry for replying late. To get the correct output array, instead of setting the state outside of the iteration I set the state in the last iteration of ```this.state.users```. – Deyvik Bhan Aug 26 '20 at 05:04