0

I have an API endpoint which has pagination. I need to implement an AutoComplete component (using MUI5 AutoComplete component) which fetches the next page's data and concatenates the result with the previous result, whenever I reach the end of the list.

I have searched the web but did not find any helpful results.

I found this similar question asked more than 2 years ago but it has not been answered till today.

The closest question to mine was this one, which also is not complete enough and I could not manage to find a way to use it.

I really appreciate any help you can provide.

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
Arad
  • 116
  • 9

1 Answers1

1

Try to combine with react-infinite-scroll-hook

Something like this:

const [sentryRef, { rootRef }] = useInfiniteScroll({
  loading: isLoading,
  hasNextPage,
  disabled: !open,
  onLoadMore: () => debouncedOptionsLoad(),
});
...
const renderSentry = () => {
  return hasNextPage || isLoading ? (
    <ListItem ref={sentryRef} key="sentry">
      Loading...
    </ListItem>
  ) : null;
};
...
const handleRenderOption = (optionProps, option) => {
  const { id, label } = option;

  if (id === "sentry") {
    return renderSentry();
  }

  return (
    <ListItem {...optionProps} key={id}>
      //for highlighting input string
      <Hightlight value={label} filter={searchString} />
    </ListItem>
  );
};
...
const sentryOption = { id: "sentry", label: '' };
...
return (
  <MuiAutocomplete 
    ...some props
    //rootRef from useInfiniteScroll hook
    ListboxProps={{ ref: rootRef }},
    filterOptions={(filterOptions) => {
      //filterOptions need for adding sentry to your options
      const shouldRenderSentry = meta.hasNextPage;

      if (shouldRenderSentry) {
        filterOptions.push(sentryOption);
      }

      return filterOptions;
    
    }},
    renderInput={(inputProps) => (
      <TextField
        value={searchString}
        onChange={ //function for change "searchString" and refetch your data }
      />
    )}
    ...
  />