-1

I am working on integrating maps in my react project. I am getting some errors. I used typescript in my project.

Below is a code which shows error:

handleChange = (e:any) => {
    this.setState({location: this.state.location})
     function initAutocomplete() {
       var input = document.getElementById('pac-input')! as HTMLInputElement;
       var searchBox = new window.google.maps.places.SearchBox(input); 
       searchBox.addListener('places_changed', function() {
         this.setState({ PlaceName: document.getElementById('pac-input').value });
               ^//---------------------#1
       });
     }
   
     initAutocomplete();
 }

This is error which I am facing:

#1 : Property 'setState' does not exist on type 'SearchBox'.ts(2339)

  • 1
    Does this answer your question? [How do you explicitly set a new property on \`window\` in TypeScript?](https://stackoverflow.com/questions/12709074/how-do-you-explicitly-set-a-new-property-on-window-in-typescript) – Roberto Zvjerković Mar 11 '21 at 11:38

2 Answers2

0

For a brief checking I think you're loosing a this context here. Try to use arrow function for initAutocomplete: const initAutocomplete = () => {...}

Vlad Diachenko
  • 387
  • 1
  • 8
0

annonymous function decleration create their own this object - you could fix you're code in 2 ways:

  • change it to an arrow function ( arrow functions inherit the outer this object)

or

   const that = this;
   searchBox.addListener('places_changed', function() {
     that.setState({ PlaceName: document.getElementById('pac-input').value });
   });
Mustafa J
  • 955
  • 8
  • 9