1

I have two ReactJS components, a page called Projects with a Table component. When I initialize the state that has Table's data like so, the Table component renders fine:

    const [tableData, setTableData] = useState([{
        client: "anna",
        name: "no",
        email: "no",
        date: new Date(),
        progress: 0
    }])

where the Table component just runs:

<tbody>
  {props.data.map((obj,index) => 
  <tr onClick = {(event) => {props.updateIndex(index)}}>
      <td>{obj.client}</td>
      <td>{obj.name}</td>
      <td>{obj.email}</td>
      <td>{obj.date}</td>
      <td>{obj.progress}</td>

  </tr>
  )}
</tbody>

However, once I attempt to overwrite this state with database data, like this, although the array of objects prints out correctly, the table cannot read the data:

  const userInfo = async () => {
    await Promise.all(res.data.map(async (el, index) => {
        const contents = await axios.get('/api/user/'+ el.userIDS[0] + '/info');
        let clientName = contents.data.firstname + ' ' + contents.data.lastname;
        let email = contents.data.email;
        let info = {
            client: clientName,
            name: el.Name,
            email: email,
            date: date,
            progress: el.progress
        };
        temp.push(info)
    }));
}

setTableData(temp)
userInfo();

Both times, the state array prints out nicely. This screenshot shows the state (tableData) both at initialization and after the userInfo() has been run, and the format seems to be the same:

enter image description here

I guess I'm just confused as to what the mistake is that I am making, since in the console both object arrays look alike, but are still off from one another. I have tried changing the structure from a 2D array to an array of objects, which I like better, but both still cause issues.

keroana
  • 69
  • 4
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Anurag Srivastava Apr 20 '20 at 16:20

1 Answers1

2

You should call setTableData(temp) inside the userInfo function:

const userInfo = async () => {
      const data = await Promise.all(
        res.data.map((el, index) => {
          return axios.get("/api/user/" + el.userIDS[0] + "/info");
        })
      );
      const temp = data.map(contents => {
        let clientName = contents.data.firstname + " " + contents.data.lastname;
        let email = contents.data.email;
        let info = {
          client: clientName,
          name: el.Name,
          email: email,
          date: date,
          progress: el.progress
        };
        return info;
      });
      setTableData(temp);
    };

Also in my suggestion, all you async call should go inside useEffect react function

Jagrati
  • 11,474
  • 9
  • 35
  • 56