Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bugfix: Refresh search results when clearing category filter #142853

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import { Search as LocalSearch, PrefixIndexStrategy } from 'js-search';
import { useEffect, useRef } from 'react';
import { useRef } from 'react';

import type { IntegrationCardItem } from '../../../../common/types/models';

Expand All @@ -16,13 +16,11 @@ export const fieldsToSearch = ['name', 'title'];
export function useLocalSearch(packageList: IntegrationCardItem[]) {
const localSearchRef = useRef<LocalSearch>(new LocalSearch(searchIdField));

useEffect(() => {
Copy link
Contributor Author

@hop-dev hop-dev Oct 6, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure why this useEffect was needed? is it best practice to only change ref.current in a useEffect? I can't find anything which says so. I've tested the search behavour and everything still works.

The bug was a race condition, the results are rendered before the useEffect is called, meaning the ref contains the stale search resaults. Removing the useEffect means the results are instantly updated removing the race.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch!
I searched about the use of ref in useEffect and actually it seems that they don't work like one would expect, causing this type of race conditions. There are some examples in this article: https://medium.com/@teh_builder/ref-objects-inside-useeffect-hooks-eb7c15198780

Thanks, TIL :)

const localSearch = new LocalSearch(searchIdField);
localSearch.indexStrategy = new PrefixIndexStrategy();
fieldsToSearch.forEach((field) => localSearch.addIndex(field));
localSearch.addDocuments(packageList);
localSearchRef.current = localSearch;
}, [packageList]);
const localSearch = new LocalSearch(searchIdField);
localSearch.indexStrategy = new PrefixIndexStrategy();
fieldsToSearch.forEach((field) => localSearch.addIndex(field));
localSearch.addDocuments(packageList);
localSearchRef.current = localSearch;

return localSearchRef;
}