I'm new to react and just started learning. I'm trying to sort the object based on the price of product. but when I try to update the state it wont change although when I do console.log() I can see the sorted products but it simply wont update on screen. I'm attaching the code below. any help would be appreciated.
When I open the app. I see all my products. but when I use the select box to sort the products it simply shows me the same products without sorted. The event is triggered. but I doubt the way I'm updating the state is wrong.
import './main.css'
import Filters from './components/Filters'
import Products from './components/Products'
import { useState } from 'react';
function App() {
const [products,setProducts]=useState([
{product_id:'1',product_name:"Razer Deathadder expert ergonomic mousepad",product_price:"20",product_path:"img/razer-deathadder-expert-ergonomic-original-imaf2z3xngbchfaz.jpeg"},
{product_id:'2',product_name:"Zotac gtx 1080 graphics card",product_price:"320",product_path:"img/grap.jpg"},
{product_id:'3',product_name:"Kingston 250 gb SSD ",product_price:"90",product_path:"img/ssd.jpg"},
{product_id:'4',product_name:"Ryzen Processor",product_price:"250",product_path:"img/ry.jpg"}
]);
let sortedProducts=[]
const sortProducts=(e)=>{
const sortBy=String(e.target.value);
switch(sortBy){
case 'plh': // sorting based on price low to high
sortedProducts=products.sort((x,y)=>{
return Number(x.product_price)-Number(y.product_price);
});
setProducts(sortedProducts); // I'm chaning the state here with my newly sorted array but its not rendering on screen
break;
case 'phl':
sortedProducts=products.sort((x,y)=>{
return Number(y.product_price)-Number(x.product_price);
});
setProducts(sortedProducts); // I'm chaning the state here with my newly sorted array but its not rendering on screen
break;
}
}
return (
<div className="App">
<div className="container">
<Filters sortProducts={sortProducts}/>
<Products products={products} />
</div>
</div>
);
}
export default App;
Here is the Products component
import Product from './Product'
function Products({products}) {
return (
<div className="product-container">
{products.map(element => (
<Product product={element}/>
))}
</div>
);
}
export default Products;
ProductscomponentAppcomponent can you render this:<div className="App">{JSON.stringify(products)}</div>and see if the products re render with the updated value? (Or just provide a codesandbox reproduction)