0

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"}]
  }

2 Answers 2

2

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_}

Sign up to request clarification or add additional context in comments.

Comments

0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.