React JS: Array is not being passed to state

Viewed 197

I have the array of objects called 'array'. When I try to pass it to the useState 'rows' to use it in my program, the data is not being copied to the rows state and it's giving me an empty array.

const project = () => {
 const [rows, setRows] = useState([]);

 const function = () => {

 var array = [{username: "username1"}, {username: "username2"}];
 
 console.log(array);
 //The output here is: 
 //(2) [{…}, {…}]
 //0: {username: 'username1'}
 //1: {username: 'username2'}
 //length: 2
 //[[Prototype]]: Array(0)

  array.map((row) => {
    return setRows(rows => [...rows, row])          
            
   })

  console.log(rows)
 //The output here is: 
 //[]
 //length: 0
 //[[Prototype]]: Array(0)

 //Another method tried
 //setRows(array)
//console.log(rows)
 //The output here is:
 //[]
 //length: 0
 //[[Prototype]]: Array(0)


 }

return (....);

}

export default project;
1 Answers
Related