I have this simple onChange function, but I have problem. When I change my input first time and for example enter "1" my variable inputOne is returns empty string:
const [inputOne, setInputOne] = useState('');
const onChange = (e) => {
setInputOne(e.target.value);
console.log(e.target.value); // first changing of input returns 1
console.log(inputOne); // first changing of input returns EMPTY string
}
<div className="container">
<input type="number" name='input1' value={inputOne} onChange={onChange} />
</div>
but when I change this input again and add one more "1"(in total 11) my console is:
console.log(e.target.value); // returns 11
console.log(inputOne); // returns 1
Why it's happening with my variable inputOne?
New code:
const [inputOne, setInputOne] = useState('');
useEffect(() => {
console.log(inputOne);
}, [inputOne])
const onChange = (e) => {
setInputOne(e.target.value);
console.log(e.target.value);
setTimeout(() => {
if(e.target.value){
const filteredpost = posts[0].filter(mfo => mfo.minPrice <= Number(inputOne));
setPostsToShow(filteredpost.slice(0, 20));
setPost(filteredpost);
}else{
const filteredpost = posts[0];
setPostsToShow(filteredpost.slice(0, 20));
setPost(filteredpost);
}}, 1000);
}
onChangefunction needs to complete first before the component reactively reruns, and only at the point the change you just made will be reflected in the variable. Until then it still has the old value (''at first, and then'1')