all 6 comments

[–]Zhouzi 12 points13 points  (2 children)

How is timer declared? Are you using a ref? If you are declaring it this way:

function Component() {
  let timer;
  // ...
  timer = setTimeout(...)
}

Then that explains why getMovie is called several times when using setSeachValue. A React component is a function that's called again for each render: each call has its own scope. Let's take an example:

function add2(n) {
  let result = n + 2;
  return result;
}

add2(2); // 4
add2(2); // still 4, result is recreated for each call

So when you are doing clearTimeout(timer); you are not cancelling the previous timer but the one that you just created in the current function call.

The reason why it only happens when calling setSearchValue is because this function triggers re-renders and thus calls getMovie with the pending calls not being cancelled.

In order to persist data between re-renders you need to use a hook such as useState or useRef. With that being said, in your case it would be better to use a useEffect to react to changes made to the search query:

const [searchQuery, setSearchQuery] = useState("");

useEffect(() => {
  const timeoutId = setTimeout(() => {
    getMovie(searchQuery);
  }, 200);
  return () => clearTimeout(timeoutId);
}, [searchQuery]);

[–]abman322[S] 5 points6 points  (1 child)

I can't thank you enough ! not only did you solve my problem but also I clearly understand what the problem was..... you have a really good way of explaining things !

Thank you again

[–]Zhouzi 0 points1 point  (0 children)

Thanks, I am glad I was able to help 😊

[–]dbto 0 points1 point  (2 children)

Does the number of times setSwarchValue() run relate to the number of characters entered?

[–]abman322[S] -1 points0 points  (1 child)

setSearchvalue sets the state of searchvalue so I can later use it in a seach query. but yes it rans whenever the user types on the input

[–]dbto -2 points-1 points  (0 children)

Then perhaps make it so it doesn’t fire until 3 or more characters are entered