Home > Back-end >  Can't get mapped array of objects to show in HTML table React
Can't get mapped array of objects to show in HTML table React

Time:12-04

I can't figure out what could be wrong i'm trying to map data that seems like this

[
  RowDataPacket { id: 1, words: 'one', numbers: 1 },
  RowDataPacket { id: 2, words: 'two', numbers: 2 }
]

into a table but it ends up showing nothing.

i have tried even with forEach but the same result, really if someone help me out with this one i would really appreciate it.

function TableCrud ({dbIo, isLoading, dbData}){
  async function triggerFetch() {
    const dbData = await dbIo('getData')
    console.log(dbData   ' dbData awaited inside TableCrud')// Console.log
  }

  function insertRow(data) {
    if (isLoading) {
      triggerFetch()
      return (
        <tr>
          <td id='no-data' colSpan='3'>Wait...</td>
        </tr>
      )
    }
    else if(data.length === 0) {
      return (
        <tr>
          <td id='no-data' colSpan='3'>Nothing to Display</td>
        </tr>
      )
    } else {
      data.map((item, index) => {
        return (
          <tr key={index}>
            <td>{item.words}</td>
            <td>{item.numbers}</td>
            <td><input className='input-check' id={'select-' index} type="checkbox"/></td>
          </tr>
        )
      })
    }
  }

  return (
    <div id='table-data'>
      <table id='table'>
        <thead>
          <tr>
            <th>Word</th>
            <th>Number</th>
            <th>Selected</th>
          </tr>
        </thead>
        <tbody id='table-body'>
          {insertRow(dbData)}
        </tbody>
      </table>
    </div>
  )
}

CodePudding user response:

Missed return sentence. It should be like:

 return data.map((item, index) => {
        return (
          <tr key={index}>
            <td>{item.words}</td>
            <td>{item.numbers}</td>
            <td><input className='input-check' id={'select-' index} type="checkbox"/></td>
          </tr>
        )
      })

So the function can return the result of map(). :)

CodePudding user response:

you can try something like this

if(!data){
    return (
    <tr>
        <td id='no-data' colSpan='3'>Nothing to Display</td>
    </tr>
 )else if(data.length !== 0){
 data.map((item, index) => {
        return (
          <tr key={index}>
            <td>{item.words}</td>
            <td>{item.numbers}</td>
            <td><input className='input-check' id={'select-' index} type="checkbox"/></td>
          </tr>
        )
      })
}
}

CodePudding user response:

I think your sample isn't valid JSON:

[
  RowDataPacket { id: 1, words: 'one', numbers: 1 },
  RowDataPacket { id: 2, words: 'two', numbers: 2 }
]

It would need to look like this to work with your map:

[
  { id: 1, words: 'one', numbers: 1 },
  { id: 2, words: 'two', numbers: 2 }
]
  • Related