I want to sort my product after I click the text "Sort by Log To High", I put "product.sort((a,b) => a.productPrice > b.productPrice ? 1 : -1)" in a onClick function but it does not work. Now it works only if I put in the const displayProduct. Any tutorial or video may I refer to? Thanks for helping.
export const Product = () =>{
const [product, setProduct] = useState([]);
const [pageNumber, setPageNumber] = useState(0)
const productPerPage = 12
const pagesVisited = pageNumber * productPerPage
const displayProduct = product
.slice(pagesVisited,pagesVisited productPerPage)
.map(product => {
return(
<div className='imageContainer ' key={product.id}>
<img src={PopularOne} className="image"/>
<div className='productName'>
<Link style={{ textDecoration:'none' }} to="/productsDetails" state={{ product:product }}>{product.productName}</Link>
</div>
<div className='productPrice'>
<h3 >RM{product.productPrice}</h3>
</div>
</div>
)
})
//product.sort((a,b) => a.productPrice > b.productPrice ? 1 : -1)
const pageCount = Math.ceil(product.length/ productPerPage)
const changePage = ({selected}) =>{
setPageNumber(selected)
}
useEffect(() => {
const fetchData = async () => {
try {
const res = await axios.get(`/routes/getProduct`);
console.log(res)
setProduct(res.data);
} catch (err) {
console.log(err);
}
};
fetchData();
}, []);
return(
<div className='product'>
<div>
<button><h3>Sort By Low to High</h3></button>
<h3>Sort By High to Low</h3>
</div>
<div className='productContainer'>
{displayProduct}
</div>
<ReactPaginate
previousLabel={""}
nextLabel={""}
breakLabel="..."
pageRangeDisplayed={5}
pageCount={pageCount}
onPageChange={changePage}
containerClassName={"pagination"}
breakClassName={"break"}
pageClassName={"page-item"} //li
pageLinkClassName={"page-link"} //a
activeLinkClassName={"page-link-active"}
/>
<Footer/>
</div>
)
}
CodePudding user response:
When you use the useState
function provided by React it returns 2 things, first is the state variable, and second is the updater function. In your case the state is product
and the updater is setProduct
.
It doesn't work because you are trying to modify the state variable, just use the updater function, and it will work.
For example:
setProduct(prevState => {
let newState = [...prevState];
newState.sort((a, b) => a.productPrice > b.productPrice ? 1 : -1);
return newState;
});
- Updater function provides the previous state, in this case it's named
prevState
. - Shallow clone the array and store it in the
newState
variable. - Mutate the
newState
array via thesort
method. - Return the
newState
. By returning here we tell React to update the state to the value ofnewState
.