skip to Main Content

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

  • Context

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).

  • Issue

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.

  • Temporary fix

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!

2

Answers


  1. You should change as below:

    setSelectedItems((items) => […items, item]);

    setState should always be a new object instead of mutating the original one.

    Login or Signup to reply.
  2.   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;
    });
    

    }, []); // try to put selectedItems : not working anymore

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search