2

I have a form that has all text elements. How come when I use this change handler function and set the state using the change event listener, it logs what the state was before the change?

const handleChange = event => {
        const { name, value } = event.target

        setSomeState(prevDateInputs => ({
            ...prevStateInputs,
            [name]: value,
        }))
        
        console.log(someState)    // ← this logs the value of the state before it was changed

    }
gmeeker99
  • 33
  • 3
  • Does this answer your question? [Why is setState in reactjs Async instead of Sync?](https://stackoverflow.com/questions/36085726/why-is-setstate-in-reactjs-async-instead-of-sync) – OFRBG Oct 21 '22 at 02:06
  • 1
    `setSomeState` function is asynchronous so your `console.log` will log the origin state. You can use `useEffect` hook for checking updated states. – Bikas Lin Oct 21 '22 at 02:22
  • 1
    You can put `console.log(someState)` outside the handleChange.So console will run multiple times.You will be able to see the previous and after that new state also.Because as mentioned in above comments setState is async so you will not be able to see updated state immediately in handleChange because it fires only once – Shubham Sharma Oct 21 '22 at 02:31

2 Answers2

1

In the recent react rfcs release you can use 'use' same as javascript async await method. more details can be found in this link https://github.com/reactjs/rfcs/pull/229

Prathap Parameswar
  • 489
  • 1
  • 3
  • 11
0

Is it essential to use setState? Could useRef work?

import {useRef} from 'react';

const App = () => {
  const inputRef = useRef(null);

  function handleChange() {
    const {name, value} = inputRef.current;
    console.log({[name] : value});
  }

  return (
    <div>
      <input
        onChange={handleChange}
        ref={inputRef}
        type="text"
        id="message"
        name="message"
      />

    </div>
  );
};

export default App;

But assuming your real use case doesn't involve a console.log, it may not matter if setState doesn't update instantly. In the below example We see the new value displayed on the screen near instantly in the h2 tag even if the console.log shows the old value:

import {useState} from 'react';

const App = () => {
  const [message, setMessage] = useState('');
  const [someState, setSomeState] = useState('');

  const handleChange = event => {

    const { name, value } = event.target
    setMessage(value)
    setSomeState({[name]:value})
    console.log('value is:', someState);
  };

  return (
    <div>
      <input
        type="text"
        id="message"
        name="message"
        onChange={handleChange}
        value={message}
      />

      <h2>{JSON.stringify(someState)}</h2>
    </div>
  );
};

export default App;

Some more details here.

shawn caza
  • 342
  • 2
  • 13