Home > Mobile >  Objects are not valid as a React child (found: object with keys {rate, count}). If you meant to rend
Objects are not valid as a React child (found: object with keys {rate, count}). If you meant to rend

Time:07-07

import logo from './logo.png';
import './App.css';
import React, { useState, useEffect } from "react";
import axios from "axios";

const idealoBackendUrl = "https://fakestoreapi.com/products"


function App() {


const render_products = (Products) => {
    console.log('.............................')
    console.log(Products)
    console.log('lllllllllllllllllllllllllllll')
    console.log(Products[0])
    console.log(typeof(Products))
    const result = Object.values(Products[0]);

    console.log(result);
    console.log('result typeee')
    console.log(typeof(result));
    console.log('................................')
    console.log(itemData)
    console.log(typeof(itemData))
   
    return <div className='category-section fixed'>
        <h2 className="text-3xl font-extrabold tracking-tight text-gray-600 category-title">Products</h2>

        <div className="m-6 p-3 mt-10 ml-0 grid grid-cols-1 gap-y-10 gap-x-6 sm:grid-cols-2 lg:grid-cols-6 xl:gap-x-10" style={{ maxHeight: '800px', overflowY: 'scroll' }}>
            {/* Loop Products */}
            {Products[0].map(product => (
                <div className="group relative shadow-lg" >
                    <div className=" min-h-80 bg-gray-200 aspect-w-1 aspect-h-1 rounded-md overflow-hidden group-hover:opacity-75 lg:h-60 lg:aspect-none">
                        <img
                            alt="Product Image"
                            src={logo}
                            className="w-full h-full object-center object-cover lg:w-full lg:h-full"
                        />
                    </div>
                    <div className="flex justify-between p-3">
                        <div>
                            <h3 className="text-sm text-gray-700">
                                <a href={product.href}>
                                    <span aria-hidden="true" className="absolute inset-0" />
                                    <span style={{ fontSize: '16px', fontWeight: '600' }}>{product.item_name}</span>
                                </a>
                                <p>Tag -</p>
                            </h3>
                            <p className="mt-1 text-sm text-gray-500">Rating: {product.rating}</p>
                        </div>
                        <p className="text-sm font-medium text-green-600">${product.current_price}</p>
                    </div>
                </div>
            ))}
        </div>
    </div>
}

const [itemData, setItemData] = useState(null);
const [error, setError] = React.useState(null);

useEffect(() => {
    getItemDataWithAxios().then(r => console.log(r));
}, []);

const getItemDataWithAxios = async () => {
    const response = await axios.get(idealoBackendUrl);
    console.log('print response data')
    console.log(response.data);
    setItemData(response.data);
};

if (error) return `Error: ${error.message}`;
if (!itemData) return <center style={{ marginTop: '200px' }}> <img src="https://icons8.com/preloaders/preloaders/1474/Walk.gif" style={{ width: '70px' }} /> </center>;


return (
      
          <div className="flex fixed flex-row">
              <div className="h-screen  bg-slate-800 p-3 xl:basis-1/5" style={{ minWidth: '65%' }}>
                  <img className="w-full" src={logo} alt="Sunset in the mountains" />
                  <div className="px-6 py-4">
                      <h1 className="text-3xl mb-2 font-bold text-white"> Idealo product catalog </h1>
                      <p className="text-gray-700 text-white">
                          by - <b style={{ color: 'orange' }}>Sithija</b>
                      </p>
                  </div>
              </div>
              <div className="ml-5  p-10 xl:basis-4/5">
                  {render_products([itemData])}
              </div>
          </div>
      // </>
   
  );
}

export default App;

I have the above piece of code and I keep getting the above-mentioned error. I cannot find the root cause for this. I noticed that when calling render_products = (Products) Products is a single object array where it should- be a 20 object array .I have tried Products[0] also with no success. Can anyone see whats wrong here ?

CodePudding user response:

Issue is in the question title, you are trying to display {product.rating} in the render_products method. It is not a number but an object of {rate, count} as keys. Please refer the below code.

import React, { useState, useEffect } from "react";
import axios from "axios";

const idealoBackendUrl = "https://fakestoreapi.com/products"


function App() {


const render_products = (Products) => {
   
    return <div className='category-section fixed'>
        <h2 className="text-3xl font-extrabold tracking-tight text-gray-600 category-title">Products</h2>

        <div className="m-6 p-3 mt-10 ml-0 grid grid-cols-1 gap-y-10 gap-x-6 sm:grid-cols-2 lg:grid-cols-6 xl:gap-x-10" style={{ maxHeight: '800px', overflowY: 'scroll' }}>
            {/* Loop Products */}
            {Products.map(product => (
                <div className="group relative shadow-lg" >
                    <div className=" min-h-80 bg-gray-200 aspect-w-1 aspect-h-1 rounded-md overflow-hidden group-hover:opacity-75 lg:h-60 lg:aspect-none">
                        <img
                            alt="Product Image"
                            src=""
                            className="w-full h-full object-center object-cover lg:w-full lg:h-full"
                        />
                    </div>
                    <div className="flex justify-between p-3">
                        <div>
                            <h3 className="text-sm text-gray-700">
                                <a href={product.href}>
                                    <span aria-hidden="true" className="absolute inset-0" />
                                    <span style={{ fontSize: '16px', fontWeight: '600' }}>{product.item_name}</span>
                                </a>
                                <p>Tag -</p>
                            </h3>
                            {/* Here was the issue */}
                            <p className="mt-1 text-sm text-gray-500">Rating: {product.rating.rate}</p>
                        </div>
                        <p className="text-sm font-medium text-green-600">${product.current_price}</p>
                    </div>
                </div>
            ))}
        </div>
    </div>
}

const [itemData, setItemData] = useState(null);
const [error, setError] = React.useState(null);

useEffect(() => {
    getItemDataWithAxios().then(r => console.log(r));
}, []);

const getItemDataWithAxios = async () => {
    const response = await axios.get(idealoBackendUrl);
    console.log('print response data')
    console.log(response.data);
    setItemData(response.data);
};

if (error) return `Error: ${error.message}`;
if (!itemData) return <center style={{ marginTop: '200px' }}> <img src="https://icons8.com/preloaders/preloaders/1474/Walk.gif" style={{ width: '70px' }} /> </center>;


return (
      
          <div className="flex fixed flex-row">
              <div className="h-screen  bg-slate-800 p-3 xl:basis-1/5" style={{ minWidth: '65%' }}>
                  <img className="w-full" src="" alt="Sunset in the mountains" />
                  <div className="px-6 py-4">
                      <h1 className="text-3xl mb-2 font-bold text-white"> Idealo product catalog </h1>
                      <p className="text-gray-700 text-white">
                          by - <b style={{ color: 'orange' }}>Sithija</b>
                      </p>
                  </div>
              </div>
              <div className="ml-5  p-10 xl:basis-4/5">
                  {render_products(itemData)}
              </div>
          </div>
      // </>
   
  );
}

export default App;

Feel free to edit the code to include your logo component and other icons, I removed them since I don't have the copy of those items.

CodePudding user response:

Try this:

...
{Products.map(product => (
...
  • Related