I'm trying to compare the current value with previous value, Which entered on the text box. But the variable not storing the value.
declaring the variable currentVal to store initial value and change currentVal value via onChange to store latest value, but its not storing the value.
I'm not sure why its happening, When I move the currentVal above function Input its storing the value and everything working fine. But I need to store the Input argument as initial value.
Here is the code below and also in codesandbox
const Input = ({ initialValue = "20" }) => {
const [value, updateValue] = useState(initialValue);
var currentVal = initialValue;
const update = event => {
console.log("currentVal at Step : 1 ::", currentVal);
var x = event.target.value;
if (currentVal !== x) {
currentVal = x;
console.log("Inside Loop :: currentVal at Step : 2 ::", currentVal);
updateValue(currentVal);
} else {
updateValue(currentVal);
}
};
return (
<>
Data :: {value} <br />
<br />
<input type="text" value={value} onChange={e => update(e)} />
</>
);
};
class App extends Component {
render() {
return (
<div className="App">
<h1> Data Test ! </h1>
<Input />
</div>
);
}
}
Question :
Why currentVal not holding/storing the updated value ?