D
D
diwlumoprif2020-04-23 12:32:33
React
diwlumoprif, 2020-04-23 12:32:33

How can you use the map array method if response is an object?

I make a request to the server

And I get the following response from the server (I get an object):

server response

{"data": [
    {
      "id":20, 
      "title":"people",
      "created_at":"2020-01-15 05:30:10",
      "updated_at":"2020-01-15 05:30:10"
    }
  ]
}


And I display the answer in the form of a table:

export default ({dataAttribute}) => (
  <table className="table">
    <thead>
      <tr>
        <th></th>
        <th>id</th>
        <th>title</th>
        <th>created_at</th>
        <th>updated_at</th>
      </tr>
    </thead>
    <tbody>
      {dataAttribute.map(item => (
        <tr key={item.id}>
          <td>{item.id}</td>
          <td>{item.title}</td>
          <td>{item.created_at}</td>
          <td>{item.updated_at}</td>
        </tr>
      ))}
    </tbody>
  </table>
);

And then I get an error:
TypeError: Cannot read property 'map' of undefined
Because the map method can only be applied to an array and my response is an object.

And I tried to change this:
{dataAttribute.map(item => (
To this:
{Object.keys(dataAttribute).map(item => (

But still I can’t display my data in the form of a table on the page, because there is an error.
Warning: Each child in a list should have a unique "key" prop.
There is a page, there are headers, but there is no data under the headers:
like this:
5ea168050d303374499323.png
What should I fix in the code to implement this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-04-23
@crystalbit

most likely dataAttribute is still null or not defined at some point. Either figure out why - for example, at the time of the mount, the data has not yet been loaded, or Object.keys(dataAttribute || {})..., if (dataAttribute) Object.keys(dataAttribute)...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question