Unknown developer
Unknown developer

Reputation: 5930

Ag grid prevents access to current value of React state variable

const [fromDate, setFromDate] = useState(moment().format('DD/MM/YY'));

function generateColumnDefs(columnDefs) {
  return columnDefs.map(columnDef => {
      if (columnDef.field === 'lob') {
        Object.assign(columnDef, {
          cellRendererFramework: lobLinkRenderer
        });
      }   
    return columnDef;
  });
}

function lobLinkRenderer(params) {
    return (
      <a onClick={() => handleClick(params)}>{params.value}</a>
    );
}

const test=()=>{
    return fromDate;
};

const handleClick = (params) => {
   let myDate1 = fromDate;
   let myDate2 = test();
}

return (
  <div>
     ...
     <button onClick={handleClick}>Test me </button>
  </div>
)

The above code is part of a React component that builds an agGrid grid. The content of a certain column is being transformed to hyperlinks through cellRendererFramework. Once clicked on these hyperlinks handleClick is invoked and populates myDate1 and myDate2. What is totally unexplained to me is why fromDate does not have its current value. In the above described case, it always have the initial value offered by useState and not the current one despite the number of changes in the state variable's value. At the same time, if clicking on Test me button, I am getting the right value for fromDate...

Upvotes: 3

Views: 2068

Answers (1)

Shuheb
Shuheb

Reputation: 2352

Please see these answers:

  1. https://stackoverflow.com/a/55156813/13129018
  2. https://stackoverflow.com/a/60643670/13129018

Based on the code you've provided, I would recommend binding fromDate to a useRef container:

const fromDateRef = useRef(null);

fromDateRef.current = fromDate;

In your methods where you are referencing fromDate, replace it with fromDateRef.current:

const test=()=>{
    return fromDateRef.current;
};

const handleClick = (params) => {
   let myDate1 = fromDateRef.current;
   let myDate2 = test();
}

Upvotes: 3

Related Questions