Search code examples
reactjsmergestatespread

React setting state using function not merging like objects


This function is called whenever MUI's data grid pro column width has been changed. I am trying to capture the "field" and "width" from the "params" and create an array of objects for all the columns that had changed width. My issue is that it just keeps adding the same object instead of merging them. For instance below I changed the width of the "wave" column two times and it just added the second change to the array.

enter image description here

I need help merging them properly

  const handleColumnSizeChange = useCallback(
    (params) => {
      setColumnDefinitions((columnDefinitions) => {
        return [
          ...columnDefinitions,
          { field: params.colDef.field, width: params.colDef.width },
        ];
      });
    },
    [columnDefinitions]
  );

  console.log(columnDefinitions);

UPDATE: I figured it out. I thought there was an easier way just using the spread in my previous function.

 const handleColumnSizeChange = useCallback(
    (params) => {
      const { field, width } = params.colDef;

      const check = columnDefinitions.some((e) => e.field === field);

      if (check) {
        const updatedDefs = columnDefinitions.map((column) => {
          if (column.field === field) {
            return { ...column, width: width };
          }

          return column;
        });

        setColumnDefinitions(updatedDefs);
      } else {
        // setColumnDefinitions((columnDefinitions) => {
        //   return [...columnDefinitions, { field: field, width: width }];
        // });

        setColumnDefinitions([
          ...columnDefinitions,
          { field: field, width: width },
        ]);
      }
    },
    [columnDefinitions]
  );

Solution

  •  const handleColumnSizeChange = useCallback(
    (params) => {
      const { field, width } = params.colDef;
    
      const check = columnDefinitions.some((e) => e.field === field);
    
      if (check) {
        const updatedDefs = columnDefinitions.map((column) => {
          if (column.field === field) {
            return { ...column, width: width };
          }
    
          return column;
        });
    
        setColumnDefinitions(updatedDefs);
      } else {
        
        setColumnDefinitions((columnDefinitions) => {
          return [...columnDefinitions, { field: field, width: width }];
        });
    
      }
    },
    [columnDefinitions]
    

    );