Edenco
Edenco

Reputation: 147

How to map an array from json that contains two arrays?

I fetch data from json and try to display one of the arrays in my componenet but I get an error that map is not a function, what do I do wrong? How to get only one array of two? Is it array I have in json or an object?

import React, { Component } from 'react';
class Customer extends Component {
constructor() {
    super();
    this.state = {
      customers : []
    };
    }

 componentDidMount() {
 fetch('myURL')
.then(response => response.json())
.then(json => this.setState({ customers: json})) 
}

render () {
    return (  
  <div>
     {this.state.customers && this.state.customers.map(cust => (
      <div>
        <h1>{cust.CustomerName}</h1>
        </div>
      )
    })}
   </div>

    )
        
}   
}
export default Customer;

And my JSON file has two arrays that looks like this:

    {
    "fields": [
    {
        "id": "Customer_ID",
        "description": "Customer ID",
        "type": "Key",
 
    },
    {
        "id": "Customer_ID",
        "description": "Customer ID",
        "type": "Key",
 
    },

],

"list_items": [{"Customer_ID":1,"CustomerName":"ABS","CustomerType":"DTS"}, 
               {"Customer_ID":2,"CustomerName":"Giu Sto","CustomerType":"STD"}]
  }

Upvotes: 0

Views: 423

Answers (2)

That Guy Kev
That Guy Kev

Reputation: 396

You did not asign the items to customers in state. You should do it like this

 componentDidMount() {
 fetch('myURL')
.then(response => response.json())
.then(json => this.setState({ customers: json.list_items})) 
}

I hope this solves your problem

Edit: this.setState({customers:json}) will change customers state to an object which is not itterable and have the value of your json file customers:{fields: [...],list_items: [...]} but you only want list_items to be assigned to customers that's why you should access list_items from json and assign it directly to customers this.setState({customers:json.list_items_}

Upvotes: 2

Saurabh
Saurabh

Reputation: 1154

try logging whether the array is present or not.

const my_json = {
  fields: [
    {
      id: "Customer_ID",
      description: "Customer ID",
      type: "Key",
    },
    {
      id: "Customer_ID",
      description: "Customer ID",
      type: "Key",
    },
  ],

  list_items: [
    { Customer_ID: 1, CustomerName: "ABS", CustomerType: "DTS" },
    { Customer_ID: 2, CustomerName: "Giu Sto", CustomerType: "STD" },
  ],
};


my_json.list_items.map(customer => console.log(customer.CustomerName))

Upvotes: 0

Related Questions