Nicolas HELIE
Nicolas HELIE

Reputation: 129

setState during componentDidMount()

I start a project with react to improve my skills on it. But on my project, I have an error when I try to set an array built from a json file in the hook ComponentDidMount(), I think this error has due to a previous one which said :

cannot read property 0 of undefined 

Do I need a specific library to parse the json file correctly?

Below the last error occur :

 Can't call setState (or forceUpdate) on an unmounted component.

The component which has the method is here :

class SimpleMap extends Component{

state={
    positions:[],
    isLoading:true
}
componentDidMount(){
    console.log(data.latlngs);
    this.switchCoord(data.latlngs);
}


switchCoord(datas){
//console.log( datas);
console.log("-----------------");
//remplacer latlngs par data pour fonctionner avec le fichier json
datas.forEach(data =>{
  let newLat;
  let newLng;
  let tableWithNewCoord =[];
  //console.log(data)
  data.forEach(d => {
      newLat = d[1];
      newLng = d[0]; 
      let switchCoordData =[newLat,newLng];
      tableWithNewCoord.push(switchCoordData);
    })
    this.setState({
      positions:[...this.state.positions,tableWithNewCoord]
    })
  })


}

The json file is import from the folder assets and it have this form :

{
"latlngs":
    [[2.367272,48.662474],[2.36523,48.663373],
    [2.360465,48.66607],[2.3557,48.667419],
    [2.352978,48.667868],[2.348893,48.669217],
    [2.34549,48.671015],[2.342767,48.672813]...]
}

thanks in advance for your help. Best Regards

Upvotes: 1

Views: 65

Answers (1)

Mohammed Abuiriban
Mohammed Abuiriban

Reputation: 510

I believe that the problem is with your switchCoord function. Simply can you try this refactored function of yours:

switchCoord(data) //actually data should be renamed to latlngs for readability 
{
  let tableWithNewCoord = [];

  data.forEach( (coord) => {
    tableWithNewCoord.push([coord[1], coord[0]])
  });

  this.setState({positions: tableWithNewCoord});
}

Upvotes: 1

Related Questions