Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to initialize data using map inside useState in ReactJs?

I’m new to React and in the assignment I’m working on, I have to show data in a AG Grid table. For that this is how I’m initializing rowData inside useState(), but it’s not shown in the webpage. The table is empty with just column names.

const ScenarioTable: React.FC<ScenarioTableProps> = (props) => {
  const { scenarios}  = props;//scenarios is an array of an object named Scenario.

  const [rowData] = useState(scenarios.map(scenario => {
    return {
      opportunityName: scenario.inputs.opportunityName,
      scenarioName: scenario.name,
      size: getSize(scenario)
    }
  }));

  const columnDefs = [
    { field: 'opportunityName', headerName: 'Opportunity Name' },
    { field: 'scenarioName', headerName: 'Scenario Name' },
    { field: 'size', headerName: 'Size'  }
  ]
   }

  return (
    <div className="ag-theme-balham" style={{height:'5000px', width:'100%'}}>
    <AgGridReact
      modules={AllModules}
      columnDefs={columnDefs}
      rowData={rowData}
    />
  </div>
)

The code inside useState() seems to have no issues but I can’t understand why no data is being shown in the table on the webpage.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If props.scenarios is a populated array on the initial render cycle then mapping it in the useState hook for the initial state value should work. If it is not available on the initial render then you’ll use an useEffect hook with a dependency on props.scenarios to update the rowData state when it [scenarios] updates.

const { scenarios } = props;

const [rowData, setRowData] = useState([]);

useEffect(() => {
  setRowData(scenarios.map(scenario => ({
    opportunityName: scenario.inputs.opportunityName,
    scenarioName: scenario.name,
    size: getSize(scenario)
  })));
}, [scenarios]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading