Akhi21
Akhi21

Reputation: 229

How to run map inside map function in Reactjs

I want my axios part should run first inside useEffect so that my state can be update first and then further I can use that.

Here is error:

TypeError: Cannot read property map of undefined

When I console it shows states is not updated it holds SwitchCOM empty array

That means it directly goes for the return statement without running useEffect axios part.

This is what my SwitchCom state look like:

SwitchCOM: {
  0: {id: "36", name: "XYZ", progress: "", details: [{id: "36", name: "XYZ", progress: ""}]},
  1: {id: "83", name: "ABC", progress: "",  details: [{id: "36", name: "XYZ", progress: ""}]},
  2: {id: "77", name: "EFG", progress: "",  details: [{id: "36", name: "XYZ", progress: "" }]}
}
const initialState = {
    SwitchCOM: [],
    isFetching: false,
    hasError: false
}


{states.SwitchCOM.map(topis => (
  <div className="item" key={topis.id}>
    <p>{topis.name}</p>
    <p>
      <progress id="file" value="32" max="100">
        {topis.progress}
      </progress>
    </p>
    {topis.activities.map(activity => (
      <table key={activity.id}>
        <tbody>
          <tr>
            <td>Name</td>
            <td>Progress</td>
            <td>Status</td>
          </tr>
          <tr >
            <td>{activity.name}</td>
            <td>{activity.prog}</td>
          </tr>
        </tbody>
      </table>
    ))}
  </div>
))}

Upvotes: 4

Views: 80

Answers (1)

Barry Michael Doyle
Barry Michael Doyle

Reputation: 10658

You are trying to map through an object which won't work. Instead you need to use Object.keys(...) to accomplish what you want here.

You should do something like this:

{Object.keys(states.SwitchCOM).map(key => (
  <div className="item" key={states.SwitchCOM[key].id}>
    <p>{states.SwitchCOM[key].name}</p>
    <p>
      <progress id="file" value="32" max="100">
        {states.SwitchCOM[key].progress}
      </progress>
    </p>
    {states.SwitchCOM[key].details.map(detail => (
      <table key={detail.id}>
        <tbody>
          <tr>
            <td>Name</td>
            <td>Progress</td>
          </tr>
          <tr>
            <td>{detail.name}</td>
            <td>{detail.progress}</td>
          </tr>
        </tbody>
      </table>
    ))}
  </div>
))}

Upvotes: 2

Related Questions