Home > Software engineering >  TypeError: Cannot destructure property 'position' of 'undefined' as it is undefi
TypeError: Cannot destructure property 'position' of 'undefined' as it is undefi

Time:12-10

I am passing a function which changes states from Parent Component to Second Component and then Second Component to Third Component and calling from it.

This results in the following error:

TypeError: Cannot destructure property 'position' of 'undefined' as it is undefined

Following is my code for reference:

export class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      address: '',
      position: {
        lat: 0,
        lng: 0,
      },
    };
    this.locationChangeHandler = this.locationChangeHandler.bind(this);
  }

  locationChangeHandler({ position, address, places }) {
    // Set new location
    this.setState({ position, address });
  }

  render(){

<SecondComponent locationChangeHandler={this.locationChangeHandler}/>

}

Second Component:

<ThirdComponent locationChangeHandler={locationChangeHandler}/>

Third Component:

<FourthComponent onChange={locationChangeHandler()}/>

How do I resolve this? I am relatively new to ReactJs and would appreciate all help.

CodePudding user response:

can you change locationChangeHandler function like this

locationChangeHandler(loc) {
    // Set new location
        if(loc && loc.position && loc.address)
        this.setState({ position: loc.position, address: loc.address });
  }
  • Related