Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda