Closed
Description
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:
loadMovies()
is called- The code immediately checks
movies
which likely still has its previous empty value 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]);
- When
movies
actually changes (after the state update fromloadMovies()
is applied) - The effect runs and correctly calls
updateSearchCount
- This ensures
updateSearchCount
is called every time there are search results
Metadata
Metadata
Assignees
Labels
No labels
Activity