2

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;  
1
  • FYI, you don't have to concat the array in setState, because you are creating a new array above with let updatedOrders=[]; anyway. Commented Aug 4, 2019 at 12:49

3 Answers 3

4

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>
);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much sir, it worked. but I didn't get how only this order doesn't have ingredients, all the orders have ingredients except this.
That I don't know :) You have to ask the guys who host the endpoint. If that worked for you, you should mark this answer as accepted. Happy coding.
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.

1 Comment

Thank you sir, it worked. but I didn't get how only this order doesn't have ingredients, all the orders have ingredients except this. Thanks for the above 3 points also :).
0

map is one of the Array methods and because you're array object(orders) is undefined this type error occurred. also you make several mistake. I refactoring orders component

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.getData = this.getData.bind(this);
  }

  getData() {
    return axios
      .get("https://reactjs-burger-builder-2607.firebaseio.com/orders.json")
      .then(response => {
        this.setState({
          orders: response.data
        });
      })
      .catch(err => console.error(err));
  }

  //this lifecycle method called when component mount
  componentDidMount() {
    this.getData();
  }

  render() {
    console.log(this.state.orders);

    const RenderOrders = () => {
      if (this.state.orders.length) {
        return <Orders orders={this.state.orders} />;
      } else {
        return <p>...loading</p>;
      }
    };

    return (
      <div>
        <Toolbar />
        <RenderOrders />
      </div>
    );
  }
}

export default Orders;

3 Comments

The array object orders is not undefined. The ingredients array in one of the orders is undefined.
@Domino987 yes one of that is undefined.
Because you said, that the orders array is undefined.

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.