reactjsreact-hooksag-gridag-grid-react

Ag-Grid Server side pagination with React: grid is resetted when an item is selected


Please go to this codesandbox example to reproduce the issue below.

I am using Ag Grid to do server side pagination on a public paginated API (Pokemon one) as explained here, and display result in the table. Moreover, I want to be able to select an item in the table, and display all selected items at the top (stored in React state).

My issue is : if you change the page (for example 2nd one), and select an item in the table by clicking on it, the Grid component is re-rendered, and you are redirected to the first page! We should stay on the second page, no reason to re-render.

I have managed it by using useCallback() on addItem function with empty dependency array, and memo on Grid component. But a new isue arises : eslint rule "exhaustive deps" is broken and we can have duplicated in the selected items list, that I want to avoid. Any ideas how to handle that issue properly in React? Thank you!


Solution

  • Finally, I have found the proper way to do it with react. Please note that it does not concern ag-grid but only react rendering mechanism.

      const addItem = useCallback((item: any) => {
        const exist = selectedItems.findIndex(
          (existingItem) => existingItem.name === item.name
        );
        if (exist === -1) {
          setSelectedItems((items) => items.concat(item));
        }
      }, []);
    
     const addItem = useCallback((item: any) => {
          setSelectedItems((items) => {
            const exist = items.findIndex(
             (existingItem) => existingItem.name === item.name
            );
            if (exist === -1) {
              return items.concat(item);
            }
         return items;
         });
     }, []);
    

    Codesandbox updated