Can't update array state using information from another state

55 Views Asked by At

I have two state objects. One is personnel, an array of 1-object arrays like this: [[{}],[{}],[{}],[{}],...]. Another is rowItems which I am trying to fill by pulling out all the objects from the inner arrays of the big personnelarray.

My end goal is to use the rowItems to create a material-ui data grid. Right now, the data grid is empty and not rendering any data, but shows the correct number of personnel items I expect (253) in the pagination display, which is weird.

Here's my code:

const [personnel, setPersonnel] = useState([]);
const [rowItems, setRowItems] = useState([]);

const handleCallback = (data) => {
    setPersonnel((prevData) => [...prevData, data]);
  };

useEffect (() => {
    console.log("personnel:", personnel) // I see all 253 arrays printed
    setRowItems((rowItems => [...rowItems, {id: '59686', first_name: 'vbn',}])) // This was for testing only, somehow hardcoding this works
    personnel?.map((row) => {
      console.log("row", row[0]); // I see the item being printed
      setRowItems(rowItems => [...rowItems, row[0]]);
      console.log("row items", rowItems) // this is empty. WHYYYY
  })
}, [personnel])


return (

    <div> // This is where I get personnel items and pass to callback
        {props.personnel.edges.map(({ node }) => {
          return (
            <Personnel
              key={node.__id}
              personnel={node}
              parentCallback={handleCallback}
            />
          );
        })}
      </div>
    
    <DataGrid
        columns={cols}
        rows={rowItems}
        pageSize={12}
    />

)


1

There are 1 best solutions below

0
x0xchoc0late On

I took jsN00b's suggestion and tried to move the setRowItems() outside of the map function like so:

useEffect(() => setRowItems(prev => ([ ...prev, ...personnel?.map(row => ({...row[0]}))])), [personnel]);

and it worked! Thanks a million!