Next.js Discord

Discord Forum

function not rerendring on state change

Unanswered
West African Crocodile posted this in #help-forum
Open in Discord
Avatar
West African CrocodileOP
I’m encountering issues with the onColumnNameUpdate function in my Ag-Grid setup. Here's a summary of the problems:

activeTab Change Not Triggering Re-render
When activeTab changes, the function does not re-render, causing it to operate on outdated state.

Incorrect Column Definitions on Subsequent Updates

First Update: Works as expected.
Example: Renaming Column 1 to Column 1a updates both columnDefs and sheets correctly.
Second Update: Operates on outdated data.
Example: Renaming Column 1a to Column 1b still references Column 1.

1 Reply

Avatar
West African CrocodileOP
const onColumnNameUpdate = useCallback(
  (newName: string, colProps: GetMainMenuItemsParams) => {
    const oldFieldName = colProps.column.getColId();
    let activeCols: ColDef[] = [];

    // Update column definitions
    setColumnDefs((prevCols) => {
      const activeSheetColDefs = prevCols[activeTab];
      if (!activeSheetColDefs) return prevCols;
      const propertyIndex = activeSheetColDefs.findIndex(
        (col) => col.field === oldFieldName
      );
      if (propertyIndex !== -1) {
        activeSheetColDefs[propertyIndex].headerName = newName.trim();
        activeSheetColDefs[propertyIndex].field = newName.trim();
        activeCols = activeSheetColDefs;
      }
      return { ...prevCols, [activeTab]: activeSheetColDefs };
    });

    // Update sheet data
    setSheets((prevSheets) => {
      const activeSheetData = prevSheets[activeTab];
      if (!activeSheetData) return prevSheets;
      const propertyIndex = Object.keys(activeSheetData[0]).indexOf(oldFieldName);
      const updatedSheetData = activeSheetData.map((row) => {
        const entries = Object.entries(row);
        entries[propertyIndex] = [newName, row[oldFieldName]];
        return Object.fromEntries(entries);
      });
      return { ...prevSheets, [activeTab]: updatedSheetData };
    });

    // Save and refresh grid
    handleSave(true);
    fetch('/api/excel-actions', {
      method: 'POST',
      body: JSON.stringify({
        name_of_file: `${wrID}.xlsx`,
        action: 'rename_column',
        column_name: oldFieldName,
        new_name: newName,
        active_sheet: activeTab,
      }),
    }).finally(() => {
      dispatch({ type: 'updateWR', payload: { isAutoSave: false } });
    });

    gridRef.current?.api?.setGridOption('columnDefs', activeCols);
    gridRef.current?.api?.refreshHeader();
  },
  [activeTab, dispatch, handleSave, wrID]
);