skip to Main Content

Let me come straight to the point the point. I was working on a React project for code like this:

import React, { useEffect, useState } from 'react'
import Footer from '../components/Footer'
import Navbar from '../components/Navbar'

export default function MyOrder () {
  const [orderData, setorderData] = useState({})
  const fetchMyOrder = async () => {
    await fetch('http://localhost:3001/api/myOrder', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email: localStorage.getItem('userEmail')
      })
    }).then(async (res) => {
      const response = await res.json()
      setorderData(response)
    })
  }

  useEffect(() => {
    fetchMyOrder()
  }, [])

  return (
    <div>
      <div>
        <Navbar />
      </div>

      <div className="container">
        <div className="row">
          {orderData !== {}
            ? Array(orderData).map((data) => {
              return data.orderData
                ? data.orderData.order_data
                  .slice(0)
                  .reverse()
                  .map((item) => {
                    return item.map((arrayData) => {
                      return (
                            <div key={arrayData.order_date}>
                              {arrayData.order_date
                                ? (
                                <div className="m-auto mt-5">
                                  {(data = arrayData.order_date)}
                                  <hr />
                                </div>
                                  )
                                : (
                                <div className="col-12 col-md-6 col-lg-3">
                                  <div
                                    className="card mt-3"
                                    style={{
                                      width: '16rem',
                                      maxHeight: '360px'
                                    }}
                                  >
                                    <div className="card-body">
                                      <h5 className="card-title">
                                        {' '}
                                        {arrayData.name}{' '}
                                      </h5>{' '}
                                      <div
                                        className="container w-100 p-0"
                                        style={{
                                          height: '38px'
                                        }}
                                      >
                                        <span className="m-1">
                                          {' '}
                                          {arrayData.qty}{' '}
                                        </span>{' '}
                                        <span className="m-1">
                                          {' '}
                                          {arrayData.size}{' '}
                                        </span>{' '}
                                        <span className="m-1"> {data} </span>{' '}
                                        <div className=" d-inline ms-2 h-100 w-20 fs-5">
                                          {' '}
                                          ₹{arrayData.price}
                                          /-{' '}
                                        </div>{' '}
                                      </div>{' '}
                                    </div>{' '}
                                  </div>
                                </div>
                                  )}
                            </div>
                      )
                    })
                  })
                : ''
            })
            : ''}{' '}
        </div>
      </div>

      <Footer />
    </div>
  )
}

I was able to render the results from the database reliably. Only the issue was that I was seeing this error:
react-dom.development.js:86 Warning: Each child in a list should have a unique "key" prop.. I don’t know why it is saying that I am using a list which I am not. I would like to know why it is happening so.

This was my result for the above code

Here is the sample database snippet

{"orderData":{"_id":"63024fd2be92d0469bd9e31a","email":"[email protected]","order_data":[[[{"id":"62ff20fbaed6a15f800125e9","name":"Chicken Fried Rice","qty":"4","size":"half","price":520},{"id":"62ff20fbaed6a15f800125ea","name":"Veg Fried Rice","qty":"4","size":"half","price":440}],"2022-08-21T15:31:30.239Z"],[[{"id":"62ff20fbaed6a15f800125f4","name":"Mix Veg Pizza","qty":"4","size":"medium","price":800},{"id":"62ff20fbaed6a15f800125f3","name":"Chicken Double Cheese Pizza","qty":"4","size":"regular","price":480}],"2022-08-21T15:32:38.861Z"]],"__v":0}}

2

Answers


  1. Chosen as BEST ANSWER

    UPDATE: I am working on this for a while. I have observer few things.

    1. I try to use a index parameter in the map to be used as key. It is no longer rendering the contents of the page. Ex: ``` order_data.map((order, index) => { ... })

    Using it in

    <div className="container">
            <div className="row">
              {orderData !== {}
                ? Array(orderData).map((data) => {
                  return data.orderData
                    ? data.orderData.order_data
                      .slice(0)
                      .reverse()
                      .map((item) => {
                        return item.map((arrayData) => {
                          return (
                                <div key={arrayData.order_date}>
                                  {arrayData.order_date
                                    ? (
                                    <div className="m-auto mt-5">
                                      {(data = arrayData.order_date)}
                                      <hr />
                                    </div>
                                      )
                                    : (
                                    <div className="col-12 col-md-6 col-lg-3">
                                      <div
                                        className="card mt-3"
                                        style={{
                                          width: '16rem',
                                          maxHeight: '360px'
                                        }}
                                      >
                                        <div className="card-body">
                                          <h5 className="card-title">
                                            {' '}
                                            {arrayData.name}{' '}
                                          </h5>{' '}
                                          <div
                                            className="container w-100 p-0"
                                            style={{
                                              height: '38px'
                                            }}
                                          >
                                            <span className="m-1">
                                              {' '}
                                              {arrayData.qty}{' '}
                                            </span>{' '}
                                            <span className="m-1">
                                              {' '}
                                              {arrayData.size}{' '}
                                            </span>{' '}
                                            <span className="m-1"> {data} </span>{' '}
                                            <div className=" d-inline ms-2 h-100 w-20 fs-5">
                                              {' '}
                                              ₹{arrayData.price}
                                              /-{' '}
                                            </div>{' '}
                                          </div>{' '}
                                        </div>{' '}
                                      </div>
                                    </div>
                                      )}
                                </div>
                          )
                        })
                      })
                    : ''
                })
                : ''}{' '}
            </div>
          </div>
    

    My confusion is that even though I am not using the list directly in my JSX. When React DOM is rendering it wrapping with <li></li> to render the contents. Causing it to throw this error message. My challenge at this stage is how to make my keys unique for every child list? I would like to understand this more in-depth. Please help me out.


  2. "orderData" is nested within an object, and it contains an array.

    PS: I do not have your API, so I have manually hard coded your object into a single state and am iterating through it.

    You can made these changes to make it work:

    Here is the codesandbox link: https://codesandbox.io/s/react-counter-functional-component-forked-xq8xfj?file=/src/Counter.js

    => Modified Logic

     <div className="container">
            {Array.isArray(orderData) &&
              orderData[0].orderData.order_data.map((order, index) => {
                const orderItems = order[0];
                const orderDate = order[1];
    
                return (
                  <div key={index}>
                    <div className="m-auto mt-5">
                      {orderDate}
                      <hr />
                    </div>
    
                    {orderItems.map((item, itemIndex) => {
                      return (
                        <div className="col-12 col-md-6 col-lg-3" key={itemIndex}>
                          <div className="card mt-3">
                            <img
                              src={item.img}
                              className="card-img-top"
                              alt="..."
                              style={{ height: "120px", objectFit: "fill" }}
                            />
    
                            <div className="card-body">
                              <h5 className="card-title">{item.name}</h5>
    
                              <div
                                className="container w-100 p-0"
                                style={{ height: "38px" }}
                              >
                                <span className="m-1">{item.qty}</span>
                                <span className="m-1">{item.size}</span>
                                <span className="m-1">{orderDate}</span>
                                <div className="d-inline ms-2 h-100 w-20 fs-5">
                                  ₹{item.price}/-
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                );
              })}
          </div>
    
    
    
      
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search