Reputation: 2245
I've been trying to find a way to use useEffect like this, but I don't think I'm doing it properly:
const [searching, setSearching] = useState(false);
function OnSearch(e) {
const searchValue = e.target.value;
useEffect(() => {
setSearching(true);
}, []);
clearTimeout(timer);
timer = setTimeout(() => {
setSearching(false);
window.location.href = '/block/' + searchValue;
}, 2000);
}
Any kind of help or direction will be appreciated.
Upvotes: 0
Views: 483
Reputation: 1074138
I assume from the useState
you've used there that this code is inside a functional component. You don't need or want useEffect
there, just remove it and do setSearching(true)
directly:
const [searching, setSearching] = useState(false);
function OnSearch(e) {
const searchValue = e.target.value;
setSearching(true);
clearTimeout(timer);
timer = setTimeout(() => {
setSearching(false);
window.location.href = '/block/' + searchValue;
}, 2000);
}
(In fact, not only do you not need it, but you can't use hooks anywhere other than the top level of a component function or hook function. So not in an event handler.)
That leaves the question of the timer
variable. It can't just be a local variable in the component function because that will get recreated on every render. For non-state instance data like that, you can use an object via useRef
, then use properties on that object, which will be consistent for the lifetime of the component:
const [instance] = useRef({});
So that gives us:
const [instance] = useRef({});
const [searching, setSearching] = useState(false);
function OnSearch(e) {
const searchValue = e.target.value;
setSearching(true);
clearTimeout(instance.timer);
instance.timer = setTimeout(() => {
setSearching(false);
window.location.href = '/block/' + searchValue;
}, 2000);
}
Side note: In JavaScript, the overwhelmingly-common convention is that only constructor functions and (in React) component functions are capitalized, not other kinds of functions. So onSearch
rather than OnSearch
. You can do what you like in your own code of course, but when working with others or asking for help, sticking to conventions helps keep communication clear.
Upvotes: 1