What I want is when I click on "products-categories" the functions takes it value and put it in my API url and change my products according to new URL. I know the method I am using is wrong so I you can suggest any way of doing it
Here is the code:
import React, { useEffect, useState } from 'react'
import './Allproducts.css'
import ForYouItem from './ForYouItem'
export default function Allproducts(props) {
const [products, setProducts] = useState([]);
const {category} = props;
const [cat1, setCat1] = useState(category)
let cat = `/${cat1}`
useEffect(() => {
// let cat = {category}
fetch(`https://fakestoreapi.com/products/category${cat}`)
.then((res) => res.json())
.then((data) => setProducts(data))
}, [])
let ChangeRoute = (c) => {
setCat1(c)
}
return (
<>
<div className="banner">
<h1>{category}</h1>
<h4>Get best items in budget</h4>
</div>
<div className="main-grid">
<div className="left-grid">
<div className="left-categories">
<h1>Collections</h1>
<h4 className='products-categories' onClick={ () => {ChangeRoute("electronics")} }>electronics</h4>
<h4 className='products-categories' onClick={ () => {ChangeRoute("jewelery")} }>jewelery</h4>
<h4 className='products-categories' onClick={ () => {ChangeRoute("men's clothing")} }>men's clothing</h4>
<h4 className='products-categories' onClick={ () => {ChangeRoute("women's clothing")} }>women's clothing</h4>
</div>
</div>
<div className="right-grid">
<div className="row ">
{products.map((product) => {
return (
<div className="col-md-4 my-2 Products">
<ForYouItem Title={product.title.slice(0, 21)} Price={product.price} Imageurl={product.image} rate={product.rating.rate} count={product.rating.count} />
</div>
)
}
)}
</div>
</div>
</div>
</>
)
}
CodePudding user response:
If what you mean is that you want to re-invoke the request to your URL any time that value changes, then you would add that value to the useEffect
dependency array:
useEffect(() => {
// let cat = {category}
fetch(`https://fakestoreapi.com/products/category${cat}`)
.then((res) => res.json())
.then((data) => setProducts(data))
}, [cat1]); // <--- here
The operation within a useEffect
happens when:
- If the dependency array has values, any time one of those values changes
- If the dependency array is empty, once when the component loads
- If the dependency array is omitted, once every render