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

92
Visualizações
Regarding reading the contents of a file and useState hook in react functional component

If you see the console logs, at line 21 the buffer variable shows undefined even though setBuffer was called before console logging the buffer. The console log of line 26 within the return statement of the App component displays fine after onChange of the file. Why does the console log at line 21 show undefined even after onChange?!

import './App.css';
import React, { useState } from 'react';
import ButtonMeta from './components/Button';
const { create } = require('ipfs-http-client');

const ipfsClient = create('https://ipfs.infura.io:5001/api/v0');

const App = () => {
  const [buffer, setBuffer] = useState(null);

  const captureFile = (event) => {
    event.preventDefault();
    const file = event.target.files[0];
    const reader = new window.FileReader();
    reader.readAsArrayBuffer(file);

    reader.onloadend = () => {
      const b = Buffer(reader.result);
      console.log('buffer', Buffer(reader.result));
      setBuffer(b);
      console.log(buffer);
    };
  };

  return (
    <div className='App'>
      {console.log(buffer)}
      <input type='file' onChange={captureFile} />
      <ButtonMeta>Submit</ButtonMeta>
    </div>
  );
};

export default App;

enter image description here

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

0

State update is an asynchronous call. So when you try to "console.log" at line 21, Value is not updated yet, thus it says undefined

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