Skip to content

Updating search count #2

Closed
Closed
@BieganskiP

Description

@BieganskiP

In search.tsx the useEffect causes some issues with updating search count

useEffect(() => {
    const timeoutId = setTimeout(async () => {
      if (searchQuery.trim()) {
        await loadMovies();

        if (movies?.length! > 0 && movies?.[0]) {
          await updateSearchCount(searchQuery, movies[0]);
        }
      } else {
        reset();
      }
    }, 500);

    return () => clearTimeout(timeoutId);
  }, [searchQuery]);

In the current implementation (the active useEffect with [searchQuery] dependency):

The problem is that even though await loadMovies() is called, the state update for movies might not have been applied yet when the code immediately checks movies?.length! > 0. This is because state updates in React are asynchronous and don't take effect right away, even with the await.

So on the first search:

  1. loadMovies() is called
  2. The code immediately checks movies which likely still has its previous empty value
  3. updateSearchCount doesn't execute because the condition fails

Here is my approach

useEffect(() => {
    const timeoutId = setTimeout(async () => {
      if (searchQuery.trim()) {
        await loadMovies();
      } else {
        reset();
      }
    }, 500);

    return () => clearTimeout(timeoutId);
  }, [searchQuery]);

  useEffect(() => {
    if (movies && movies.length > 0 && searchQuery.trim()) {
      updateSearchCount(searchQuery, movies[0]);
    }
  }, [movies]);
  1. When movies actually changes (after the state update from loadMovies() is applied)
  2. The effect runs and correctly calls updateSearchCount
  3. This ensures updateSearchCount is called every time there are search results

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions