Y
Y
yumakaev2020-01-09 02:52:49
React
yumakaev, 2020-01-09 02:52:49

How to get rid of initial value in useState?

Good evening!
How to get rid of initial value in input?
When I start writing, the previous value falls into the console as the first character (it's also the initial one)
https://codesandbox.io/s/wizardly-williamson-nxrl7

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vadim, 2020-01-09
@MrDecoy

You don't have the problem you describe, because it works a little differently than you, I suppose, think.

const Logic = () => {
  const [inputValues, setInputValues] = useState('');
  console.log('1)', inputValues);
  const onChangeInput = e => {
    setInputValues((currentState) => {
      console.log('2) current', currentState); 
      return e.target.value});
    console.log('3)', inputValues);
  };

  return <View inputValues={inputValues} onChangeInput={onChangeInput} />;
};

// Будем вводить букву 'a' в инпут. В итоге в консоле получим:
// 1)"" <-- из-за useState('');
// 2) current "" <-- так как значение мы ещё не обновили, то получаем то же начальное значение из useState('');
// 3) "" <-- вызвывается ПОСЛЕ setInputValues, тем не менее, имеет ещё не обновлённое значение.
// 1) a <-- произошло изменение состояния, компонент перерисовался.

Further, depending on what you want to do,
display the value either in "1)" - this is the output with a new state but before redrawing,
or in "3)" You need to output e.target.value.
The state change operation is asynchronous and React can bundle multiple state changes into one for optimization.

N
Nikolay Matyushkin, 2020-01-09
@Devilz_1

I will add to the above comment from Vadim.
Sometimes there is a need to carry out any manipulations with the data immediately after we have changed them in the function. Let's take the author as an example:

import React, { useState } from "react";
import "./styles.css";

const View = ({ inputValues, onChangeInput }) => {
  return <input type="text" value={inputValues} onChange={onChangeInput} />;
};

const Logic = () => {
  const [inputValues, setInputValues] = useState("");

  const onChangeInput = e => {
    setInputValues(e.target.value);

    // *** Здесь мы хотим взять новые данные и что-то с ними сделать (в данный
    // момент мы просто выводим в консоль)
    console.log(inputValues);
  };

  return <View inputValues={inputValues} onChangeInput={onChangeInput} />;
};

export default Logic;

*** Here the data is outdated, Vadim described it, and I agree with him. But still, there is an option to use the data immediately after changing it, and unfortunately this option looks much less aesthetically pleasing in hooks than in classes.
The fact is that classes use setState (cap) to change the state. setState takes a mutable object as its first parameter, and it takes a callback as its second (optional) parameter, in which you can get the already changed state. Below is an example of the author, where the functional Logic component is converted into a class component of the same name. Here. When entering characters in input, in the console we will receive characters in order, i.e. we will see the current state
To achieve the same result with the author, you need to subscribe to changing the inputValues ​​parameter in the useEffect hook. Here. Now we also see the actual data when entering characters in the input.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question