JavaScript TypeError: Cannot read property 'map' of undefined while fetching data from the server typeerror cannot read property,typeerror cannot read property 'map&#

I am fetching data from the server and getting the data successfully as you can see in the screenshot, I also checked my code. my code is working properly when I take data manually, but I don't know why I am getting this error:

TypeError: Cannot read property 'map' of undefined

enter image description here

Orders.js file:

import React, { Component } from 'react';
import Toolbar from '../../components/Navigation/Toolbar/Toolbar';
import Order from '../../components/Order/Order';
import axios from 'axios';

class Orders extends Component {

    constructor(){
        super();
        this.state={
            orders:[]
        }

        this.componentDidMount=(event) =>{

            axios.get('https://reactjs-burger-builder-2607.firebaseio.com/orders.json')
              .then(response =>{
                console.log(response.data)
                let updatedOrders=[];
                for(let key in response.data)
                {
                    updatedOrders.push(response.data[key]);
                }
                this.setState({
                    orders:[].concat(updatedOrders),
                });
            })
        }     
}

  render() { 

      console.log(this.state.orders);

      let allOrders='loading..'; 
      if(this.state.orders){
          allOrders= <Order orders={this.state.orders}/>
      }

    return (
        <div>
        <Toolbar/>
        {allOrders}
        </div>    
    );
  }
}

export default Orders;

Order.js file

import React from 'react';
import classes from './Order.css';

const Order =(props) =>{

    console.log(props.orders);

    return(  
        <div>
         {props.orders.map(order =>
          <div className={classes.order} key={Math.random()}>
              <span>name: {order.name} </span><br/>
              <span>contact: {order.contact} </span><br/>
              <span>address: {order.address} </span><br/>
              <span>Price: {order.price} Rs </span><br/>
              <p><span>ingredients: </span>
              {order.ingredients.map(ingredient =>
                 <span key={Math.random()} className={classes.ingredients}>{ingredient.name} ({ingredient.qty}) </span>
               )}
              </p>
         </div>
        )}

        </div>
    );
}

export default Order;  
Answer:1

Not all orders have ingredients (order: -LlR57Tm3bO2xX31ywFq). This is why it fails for certain orders. You have to check first if the order has ingredients.

return(  
    <div>
     {props.orders.map(order =>
      <div className={classes.order} key={Math.random()}>
          <span>name: {order.name} </span><br/>
          <span>contact: {order.contact} </span><br/>
          <span>address: {order.address} </span><br/>
          <span>Price: {order.price} Rs </span><br/>
          <p><span>ingredients: </span>
          {order.ingredients ? order.ingredients.map(ingredient =>
             <span key={Math.random()} className={classes.ingredients}>{ingredient.name} ({ingredient.qty}) </span>
           ) : 'No ingredients'}
          </p>
     </div>
    )}

    </div>
);
Answer:2

I suppose there is an order without ingredients. Just check if ingredients are there before mapping:

{Array.isArray(order.ingredients) && order.ingredients.map(ingredient =>
  <span key={Math.random()} className={classes.ingredients}>{ingredient.name} ({ingredient.qty}) </span>
)}

By the way, your code contains a couple of problems:

  1. Do not use Math.random() as list element key, this is the worst possible input to key element (it's better to leave key alone). Refer to https://reactjs.org/docs/lists-and-keys.html
let updatedOrders=[];
for(let key in response.data)
{
  updatedOrders.push(response.data[key]);
}
this.setState({
  orders:[].concat(updatedOrders),
});
  1. This part of code makes no sense. Especially naming updatedOffers and [].concat(updatedOrders).
  2. Why do you assign a value to componentDidMount in constructor rather than default method declaration in ES6? You mix ES5 and ES6.
Answer:3

As suggested here, I should use canvas renderer so that images can be displayed in nodes. First of all I create a graphClass: graphClass.g = { nodes: [], edges: [] } Then, I create each node:...

As suggested here, I should use canvas renderer so that images can be displayed in nodes. First of all I create a graphClass: graphClass.g = { nodes: [], edges: [] } Then, I create each node:...

I am working on an Angular project where I want to catch all the encCharge to add them to give a total of all the encCharge in my cf's with a for function. This is my array : produits = [ { ...

I am working on an Angular project where I want to catch all the encCharge to add them to give a total of all the encCharge in my cf's with a for function. This is my array : produits = [ { ...

Result shows "n.split is not a function" unless i include n=n+" " the following code.What does third line mean? function reverse_a_number(n) { n = n + ""; return n.split("").reverse()....

Result shows "n.split is not a function" unless i include n=n+" " the following code.What does third line mean? function reverse_a_number(n) { n = n + ""; return n.split("").reverse()....

  1. write javascript function in html
  2. write javascript function in typescript
  3. write javascript function in js file
  4. write javascript function in angular 6
  5. write javascript function in html tag
  6. write javascript function in ts file
  7. write javascript function in onclick
  8. write javascript function in console
  9. write javascript function inside onclick
  10. write javascript function in code behind c#
  11. write javascript function
  12. write javascript function in php
  13. write javascript function in react
  14. write javascript function inside html
  15. write javascript function with parameter
  16. write javascript function in c#
  17. write javascript function with callback
  18. write javascript function with return value
  19. write javascript function for add(3)(4)
  20. write javascript function in href

I have an AngularJS Application I am trying to post a message through. I am successfully able to log the user in, get the access token, and I have ensured I have my domain in the JavaScript Origins ...

I have an AngularJS Application I am trying to post a message through. I am successfully able to log the user in, get the access token, and I have ensured I have my domain in the JavaScript Origins ...

  1. cors error when calling api
  2. cors error when calling api from angular
  3. cors error when using fetch
  4. cors error in angular
  5. cors error in chrome
  6. cors error in angular 6
  7. cors error in react
  8. cors error in angular 7
  9. cors error in node js
  10. cors error on localhost
  11. cors error on post request
  12. cors error in spring boot
  13. cors error in ajax
  14. cors error on same domain
  15. cors error in react js
  16. cors error in javascript
  17. cors error in angularjs
  18. cors error in angular 8
  19. cors error in web api
  20. cors error in angular 5