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

Unknown developer
  • 5,414
  • 13
  • 52
  • 100

1 Answers1

3

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();
}
Shuheb
  • 2,012
  • 1
  • 4
  • 6
  • `refContainer` sounds like a bad name c.f. `fromDateRef`... – AKX May 20 '21 at 10:29
  • Yes. That works. Could you please add some details to your answer and explain why that happens? – Unknown developer May 20 '21 at 10:52
  • I had this issue before, this was the fix for me. Please see the answer here for an explanation (I'll add it on top of my answer as well): 1) https://stackoverflow.com/questions/57847594/react-hooks-accessing-up-to-date-state-from-within-a-callback/60643670#60643670 2) https://stackoverflow.com/a/55156813/13129018 – Shuheb May 20 '21 at 11:16