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

[BUG]: incorrect behavior on debonuce of onSearch in useSelect #6096

Closed
Dominic-Preap opened this issue Jul 3, 2024 · 5 comments · Fixed by #6125 or #6154
Closed

[BUG]: incorrect behavior on debonuce of onSearch in useSelect #6096

Dominic-Preap opened this issue Jul 3, 2024 · 5 comments · Fixed by #6125 or #6154
Assignees
Labels
bug Something isn't working

Comments

@Dominic-Preap
Copy link
Contributor

Dominic-Preap commented Jul 3, 2024

Describe the bug

When use onSearch in useSelect, we see that fetch requests called repeatedly after delay on debonuce value. Video demo is below.

refine.mp4

Steps To Reproduce

Sample code:

const { onSearch, queryResult } = useSelect({
  resource: 'test',
  debounce: 1500,
  searchField: 'search'
});

return <input onChange={e=>onSearch(e.currentTarget.value)}/>

Expected behavior

It should delay then executed onSearch once or throttling onSearch function. After checking in package it seems to use debounce from loadash. I suggest using use-debounce or any libs that are similar.

Packages

  • @refinedev/core

Additional Context

This will lead to multiple requests to the server if not handle properly.

@Dominic-Preap Dominic-Preap added the bug Something isn't working label Jul 3, 2024
@aliemir
Copy link
Member

aliemir commented Jul 3, 2024

Hey @Dominic-Preap, I've tested the behavior in our test environment and also used your code in a project but could not reproduce the issue. Looks like onSearch is working as expected in both cases. Can you please provide a small reproducible example?

@Dominic-Preap
Copy link
Contributor Author

Let me add testing repo.

@Dominic-Preap
Copy link
Contributor Author

Dominic-Preap commented Jul 3, 2024

@aliemir Here is the test repo. I think I know the problem is. We use Controller from hook-from and render autocomplete input inside & not using useCallback that cause it fetch multiple. I'm not sure if it should handle by user or refine.

// blog-posts/create.tsx

// Page
<Controller
  control={control}
  name="category"
  render={({ field: { onChange, value }, fieldState: { error } }) => (
    <CategorySearch
      error={error?.message}
      onChange={onChange}
      value={value}
    />
  )}


const CategorySearch: React.FC<Props> = ({ onChange, value, error }) => {
  const { onSearch, queryResult } = useSelect({
    resource: "categories",
    debounce: 1500,
    searchField: "title",
  });

  // ! Debounce working okay <---- SWITCH FUNCTION HERE
 const handleChange = useCallback((value: string) => {
    onChange?.(value);
    onSearch(value);
  }, []); 

  // ! Debounce run fetch multiple <---- SWITCH FUNCTION HERE
  const handleChange = (value: string) => {
    onChange?.(value);
    onSearch(value);
  };

  return (
    <label>
      <span style={{ marginRight: "8px" }}>Category</span>
      <input
        onChange={(e) => handleChange(e.currentTarget.value)}
        value={value}
      />
      <span style={{ color: "red" }}>{error}</span>
      <ul>
        {queryResult.data?.data.map((x) => (
          <li key={x.title}>{x.title}</li>
        ))}
      </ul>
    </label>
  );
};

@aliemir
Copy link
Member

aliemir commented Jul 4, 2024

Hey @Dominic-Preap, just checked your repro and the code you've provided. Confirming the issue about the debounced callback of onSearch. Thank you for the detailed explanation. I've tested out a fix in the useSelect, let me explain it below and maybe you can create a PR for it 🚀

onSearch: onSearchFromProp,

This prop also causes re-renders if it's inlined. We can store it in a ref like this:

  /**
   * To avoid any changes in the `onSearch` callback,
   * We're storing `onSearchFromProp` in a ref and accessing it in the `onSearch` callback.
   */
  const onSearchFromPropRef = useRef(onSearchFromProp);

  useEffect(() => {
    onSearchFromPropRef.current = onSearchFromProp;
  }, [onSearchFromProp]);

We should move debounce into the onSearch and memoize it:

Current:

const onSearch = (value: string) => {
if (onSearchFromProp) {
setSearch(onSearchFromProp(value));
return;
}
if (!value) {
setSearch([]);
return;
}
setSearch([
{
field: searchField,
operator: "contains",
value,
},
]);
};

Wrapping it with useMemo and using debounce in the definition:

  const onSearch = useMemo(() => {
    return debounce((value: string) => {
      if (onSearchFromPropRef.current) {
        setSearch(onSearchFromPropRef.current(value));
        return;
      }

      if (!value) {
        setSearch([]);
        return;
      }

      setSearch([
        {
          field: searchField,
          operator: "contains",
          value,
        },
      ]);
    }, debounceValue);
  }, [searchField, debounceValue]);

Then we can just update the return statement:

return {
  queryResult,
  defaultValueQueryResult,
  options: combinedOptions,
-   onSearch: debounce(onSearch, debounceValue),
+   onSearch,
  overtime: { elapsedTime },
};

Let me know if you can work on this and open up a PR 🙏

@Dominic-Preap
Copy link
Contributor Author

Thanks for your explanation and sure I'll check it out and make a PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants