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

164
Visualizações
React: FileReader onloadend doesn't recognize "this" if defined in a component method

I define a method in a React class component as follows

onSaveAudio = (e) => {
    e.preventDefault();
    const { audioBlob } = this.state;

    let reader = new FileReader();

    reader.onloadend = function () {
        const base64 = reader.result;
        const bstr = base64.split(',')[1];
        console.log(bstr);
        console.log('this.props', this.props);
        this.props.onSaveAudio(bstr);
    }

    reader.readAsDataURL(audioBlob);
    
    }

At the console.log('this.props', this.props) line, it's printing "undefined"; at the this.props.onSaveAudio line, an error is thrown:

Uncaught TypeError: Cannot read property 'onSaveAudio' of undefined at FileReader.reader.onloadend (recorder.js:300)

My understanding is that "onloadend" is triggered after the "reader" finishes reading "audioBlob". I need to call the this.props.onSaveAudio in the "onloadend" function, because if I call it outside of "onloadend", I can't time the call to after the reading finishes and "reader.result" is ready, and "bstr" would resolve to undefined with the wrong timing; but if I call the this.props.onSaveAudio within "onloadend", then "this" is not recognized. Seems to be a dilemma.

My guess is I need a solution to either bind "this" within "onloadend", or be able to somehow time a this.props.onSaveAudio call outside of the "onloadend" function, after the "onloadend" function finishes execution.

Any advice?

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

0

One way I found is to use an arrow function when defining "reader.onloadend".

    reader.onloadend = () => {
        const base64 = reader.result;
        const bstr = base64.split(',')[1];
        console.log(bstr);
        console.log('this.props', this.props);
        this.props.onSaveAudio(bstr);
    }

this.props will be defined in this case

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