Search code examples
reactjsag-gridredux-toolkitrtk-query

AG Grid with Redux Toolkit Query?


Im trying to integrate AG Grid server side model with Redux Toolkit Query but problem is I have external parameters that changes, but did not find how to handle this.

I have pagination/filters/sorting on, I think I cant just override the datasource or I might lose them?

Heres an example

function MyGrid({ param1, param2 }: props): ReactElement {
    // param1/param2 are updated here
    const [triggerPostData] = usePostDataMutation();

    const createDatasource: () => IServerSideDatasource = useCallback(() => {
        return {
            getRows: (parameters): void => {
                // param1/param2 arent updated here
                triggerPostData({ param1, param2, rowsRequestData: parameters.request })
                    .unwrap()
                    .then((data) => {
                        parameters.success({
                            rowData: data.results,
                            rowCount: data.resultCount
                        });
                        return parameters;
                    })
                    .catch(() => {
                        parameters.fail();
                    });
            }
        };
    }, [param1, param2, triggerPostData]);

    const onGridReady = useCallback(
        (parameters: GridReadyEvent): void => {
            parameters.api.setServerSideDatasource(createDatasource());
        },
        [createDatasource]
    );

    const agGridProperties: AgGridReactProps = {
        columnDefs,
        rowModelType: 'serverSide',
        cacheBlockSize: paginationPageSize,
        onGridReady
    };

    return <AgGridReact {...agGridProperties} />;
}

Solution

  • In your code, datasource is set only once (in the greadReady callback). Then when param1 and param2 are changed it makes new createDatasource function which is never used by grid. I would suggest setting datasource via AgGridReact property serverSideDatasource

    function MyGrid({ param1, param2 }: props): ReactElement {
      // param1/param2 are updated here
      const [triggerPostData] = usePostDataMutation();
    
      const serverSideDatasource: IServerSideDatasource = useMemo(() => {
        return {
          getRows: (parameters): void => {
            // param1/param2 arent updated here
            triggerPostData({ param1, param2, rowsRequestData: parameters.request })
            ...
          },
        };
      }, [param1, param2, triggerPostData]);
    
      const agGridProperties: AgGridReactProps = {
        columnDefs,
        rowModelType: 'serverSide',
        serverSideDatasource,
        cacheBlockSize: paginationPageSize,
      };
    
      return <AgGridReact {...agGridProperties} />;
    }
    

    UPD: As @phry pointed out, the server-side row model is designed around an imperative approach through the getRows method, so it would not be practical to use RTK Query with Server-side model.