Answer the question
In order to leave comments, you need to log in
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
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 <-- произошло изменение состояния, компонент перерисовался.
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;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question