Skip to content
Advertisement

How do I map an through an array of objects and display each object individually? I want each pizza order to show

I am not sure how to iterate through each order and show them as individual orders. The api response looks like this…

0:

Crust: “THIN”

Flavor: “CHEESE”

Order_ID: 2

Size: “S”

Table_No: 5

Timestamp: “2019-12-03T18:21:08.708470”

And can go on to have as many orders as possible. I do not need the Order_ID showing so maybe that is a way to iterate through?

import React, { Component } from 'react'
import axios from 'axios';

export default class Orders extends Component {
    constructor() {
        super();
        this.state = {
            order: "no orders yet",
            crust: "no crust selected",
            // flavor: "no flavor selected",
            // size: "no size selected",
            // table: "place an order first",
            // timestamp: "place an order first"
        };
    }

    handleButtonClick = () => {
        axios.get("/orders").then(response => {
            this.setState({
                orders: response,
                crust: response.data[0].Crust
                // flavor: response.data[0].Flavor
                //etc..
            });
        })
    }

    render() {
        return(
            <div>
                <button onClick={this.handleButtonClick}></button>
                <h1>orders are:</h1>
                <p>Crust: {this.state.crust}</p>
            </div>
        );
    }

}

export { Orders }

Advertisement

Answer

From what I could figure out from your codeblock, this should work. Just set the orders array to the response.data and then iterate over the orders array in your render function.

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

    handleButtonClick = () => {
        axios.get("/orders").then(response => {
            this.setState({
                orders: response.data
            });
        })
    }

    render() {
        const orderData = this.state.orders.map(order => {
return })
        return(
            <div>
                <button onClick={this.handleButtonClick}></button>
                <h1>orders are:</h1>
                {this.state.orders.map((order) => (
                    <p>Flavor: {order.flavor}</p>
                    <p>Crust: {order.crust}</p>
                ))}
            </div>
        );
    }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement