0

Compiled with problems:X

ERROR

src\component\Products.jsx Line 8:34: React Hook "useState" is called in function "getAllProducts" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use" react-hooks/rules-of-hooks

I'm trying to use useState, what is the best way to fetch the data from database to frontend

import React, { useState } from 'react';
import { NavLink } from 'react-router-dom';
import DATA from '../Data';


const getAllProducts = () => {

    const [products, getproducts] = useState({
        title : '',
        price : '',
        image : ''
    });

    const {title, price, image}=  products;
     let getproduct = fetch('http://localhost:6000/products/allProducts', {
        method : 'GET',
        headers : {
            'Content-Type':'application/json'
        },
        body : JSON.stringify({
            title, price, image
        })
    
})

    const cardItem = (item) => {
        return(

            
            <div className="card mx-3 my-5 py-3 px-2" key={item.id} style={{width: "15rem"}} id="cards">
                        <img src={item.image} className="card-img-top" alt={item.title} />
                        <div className="card-body text-center">
                            <h5 className="card-title fw-bolder" id="para">{item.title}</h5>
                            <p className="lead fw-bold" id="para">${item.price}</p>
                            <NavLink to={`products/${item.id}`} className="btn btn-outline-danger fw-bolder px-5 rounded-pill" id="para">Buy Now</NavLink>
    
                        </div>
                    </div>      
            );
    }

    return (
        <div>
            <div className="container py-2 mt-5 pt-5">
                <div className="row">
                    <div className="col-12 text-center">
                        <h1 className="display-6 fw-bolder text-center" id="late">Latest Collections</h1>

                        <hr/>
                    </div>
                </div>
            </div>
            <div className="container" id="products">
                <div className="row justify-content-around">
                    {getproduct.map(cardItem)}
                </div>
            </div>
        </div>
        );

}

export default getAllProducts;
Ms.Grepper
  • 11
  • 5
  • As the error points out, React components names must start with an uppercase letter. Your component is named "getAllProducts" when it should be "GetAllProducts". In fact, I would just name it "Products". Also, regarding your state, you should name it "products" and "setProducts" for your setter function. Check out React's documentation for more details about these conventions. – ivanatias May 21 '22 at 08:05

1 Answers1

0

Hi

First I notify you of errors in your code and then expose you a solution:

In getAllProducts you use a useState but you can't use it this way, it's not a React component.

You also call getAllProducts.map but getAllProducts doesn't return any data array

In your useState the initial value represents ONLY one object of your data array


I would advise you this one , it's near of what you have done.

We create a method to get the data, a state to store the data and we display them conditionally

In my example below I use the axios library, it is an alternative to the fetch method that you use but the principle remains the same with the fetch method (except for one line of code)

I hope it helps you

import React , {useState,useEffect} from 'react'
import axios from 'axios'

const getAllProducts = async ()=>{
//Here is the fetch method
try{
 const fetchQuery = await axios.get('my-url')
return fetchQuery.data

}
catch(error){
    console.log(error)
}}



const CardItem = (props)=>(
  //here you card component that will be mapped
  <div>
    <p>{props.data.title}</p>
    <p>{props.data.price}</p>
  </div>
  )

const MappedCards = ()=>{
    //Our initial state is a empty array
  const [allProducts,setProducts] = useState([])
  
    
  useEffect(()=>{
  // I use the hook useEffect so when the MappedCards component is mounted
  // I can fetch data and use the setProducts method
    
    const initProducts = async ()=>{
      const data = await getAllProducts()
      setProducts(data)
    }
    
    //I call the method to initProducts
    initProducts()
    
  },[])
  
  
  // I can even make something really cool here

  if(allProducts.length === 0){
   return <span>Loading data...</span> 
  }

  // Now when allProducts will be filled with data I'll show this
  
  return (<div className="my-container">
  <h1>My shop</h1>
  {allProducts.map(product => (<CardItem key={product.id} data={product} />}
  </div>)
  
}
  

export MappedCards

adevinwild
  • 278
  • 4
  • 8
  • Can you please post the code as code block and not as screenshot? This is very unaccessible by visually or otherwise impaired users. Thanks! – lxg May 21 '22 at 08:07
  • @horhorou Sir I still have an error, the code I wrote is above – Ms.Grepper May 21 '22 at 10:17