-1

In my React app using functional components, I have a a local state (myObj) which is populated via context object from parent (based on API response). I use this local state to populate the AgGrid and within this grid, I have a row-level Edit link using cellRenderer.

Now, I want to access the local state (myObj) within this cellRenderer, but I am getting it as empty object {}

I have tried adding cellRendererParams: {myObj: myObj}, but still does not work.

Do I need to add something more to access function component state inside cellRenderer

function MyChildComponent(props) {
    const [gridData, setGridData] = useState([]);
    const [myObj, setMyObj] = useState({
        gridItems: [{
            fields: [{
                field1: {},
                field2: {}
            }]
        }]
    });
    
    useEffect(() => {
        //API call to set myObj with data (includes grid data within the API response)
    }, [myContextObjWithData]);
    
    useEffect(() => {
        if (myObj && myObj.gridItems && myObj.gridItems.length > 0) {
            setGridData([{
                'field1': 'Primary',
                'field2': 'F1'
            }, {
                'field1': 'Secondary',
                'field2': 'F2'
            }])
        }
    }, [myObj])
    
    
    setMyColumns([
        {
            headerName: 'Col 1',
            field: 'field1'
        }, {
            headerName: 'Col 2',
            field: 'field2'
        }, {
            headerName: '',
            field: '',
            cellRendererParams: {myObj: myObj},
            cellRenderer: (params) => {
                console.log(myObj); // Returns empty object
            }
        }
    ])
    
    
    return (
        <>
            <MyAgGrid
                id="myGrid"
                columnDefs={myColumns}
                rowData={gridData}
                {...props}
            />
        
        </>
    ); 
}   
copenndthagen
  • 49,230
  • 102
  • 290
  • 442

1 Answers1

0

Try updating myColumns state within a useEffect with myObj has one of its dependencies.

The lifecycle of this component is whenever this component gets mounted, The local state will be created and trigger the useEffect corresponding to those states which further updates the state. In your example, you are calling without a useEffect hook which will cause the code to run earlier and console an empty object.