1

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

  • 2
    State updates are generally queues of tasks that are batch processed asynchronously so the state will be `undefined` at that point. In functional components you can use [`useEffect`](https://reactjs.org/docs/hooks-effect.html) to log the state when it has changed: `useEffect(() => console.log(buffer), [buffer]);`. – Andy Sep 06 '21 at 22:02

1 Answers1

2

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

Niharika
  • 36
  • 1