Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
How to update state inside an addListener React Class Component

Greetings to everyone,

I have really no experience in working with class components as I have been using the normal functional easy ones but recently started a project that requires the class component,

I have the following state variable -

  this.state = {
      current: "City X"
    };

Now in the methods for this class, I have a function -

 codeAddress(geocoder) {
        var marker;
        var data = this.state.data;
    
     marker.addListener("click", () => {
    
             
              // On click - The state value of 'current' should update to another value.

this.setState({current: 'City Y'});

                
    
                  setTimeout(() => {
                    var pointA = new google.maps.LatLng(54.976713, -1.60728);
    
                    
    
                    var request = {
                      origin: pointA,
                      destination: location,
                      travelMode: 'DRIVING'
                    };
                    directionsService.route(request, function (result, status) {
                      if (status == 'OK') {
                        directionsRenderer.setDirections(result);
                      }
                    });
    
    
                  }, 2000)
                });
    }

However this code gives an error that TypeError: Cannot read properties of undefined (reading 'setState')

I have binded all the functions in the constructor and tried a bunch of different techniques of updating the state value but haven't been able to figure it out exactly just yet.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

For what it looks like it seems like you have a problem with the scope of this, Did you bind the codeAddress Function inside the constructor?

constructor( props ){
    super( props );
    this.codeAddress = this.codeAddress.bind(this);
  }

So what is happening is that JavaScript is trying to access the this but inside a normal Function (not an arrow function) and the this is just an object with no properties in your case. With the bind Function we are binding the this we have in our class to that function so when you call this It will get you the this Of the class itself and will let you access all of it’s properties

about 4 years ago · Juan Pablo Isaza Relatório

0

Follow up on my previous answer One solution you can do is to add a binding function and call it inside the callback

const setCurrentOnMarkerClick = (function() { 
        this.setState({current: 'City Y'});

            

              setTimeout(() => {
                var pointA = new google.maps.LatLng(54.976713, -1.60728);

                

                var request = {
                  origin: pointA,
                  destination: location,
                  travelMode: 'DRIVING'
                };
                directionsService.route(request, function (result, status) {
                  if (status == 'OK') {
                    directionsRenderer.setDirections(result);
                  }
                });


              }, 2000)
            });          
    }).bind(this);

 marker.addListener("click", setCurrentOnMarkerClick)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda