When I'm using the input
s ref={inputRef}
and using setState
the value of the state
is always one step behind - meaning, it owns its previous value
.
When I type any string inside the input field, in the first button's it will have an empty string, only in the second button's click it will have that string I entered and will fire the console.log('searchString', searchString);
TWICE!
I was adviced in my previous question, that instead of calling onChange={(e) => onChangHandler(e)}
each time I press a letter in input field I can just take the whole value when clicking the button for activeSearch()
ONE time only.
function Header({ setingResults }) {
const [productsObj, setObjs] = useState([]);
const [searchString, setString] = useState('');
const inputRef = useRef();
// const onChangHandler = (e) => {
// setString(e.target.value);
// };
const activeSearch = () => {
setString(inputRef.current.value);
if (searchString.length > 0) {
console.log('searchString', searchString);
setingResults(searchString);
}
};
return (
<div>
<header className='header-shop'>
Welcome to Vitamins Store
<br />
<input
placeholder='Search here'
ref={inputRef}
// value={searchString}
// onChange={(e) => onChangHandler(e)}
/>
<button onClick={activeSearch}>Search</button>
</header>
</div>
);
}
export default Header;
Anybody knows here whats the probelm ?
I'll be glad for some help.