I have some array of products inside filteredProducts
variable and wanted to sort them according to the price and newly added products.
When using prevState like this without having { }
in the callback function, the code runs fine.
useEffect(() => {
if(sort === "newest") {
setFilteredProducts((prevState) =>
[...prevState].sort((a, b) => a.createdAt - b.createdAt)
);
}
else if (sort === "asc") {
setFilteredProducts((prevState) =>
[...prevState].sort((a ,b) => a.price - b.price)
);
}
else {
setFilteredProducts((prevState) =>
[...prevState].sort((a, b) => b.price - a.price)
);
}
}, [sort]);
But when using { }
for the prevState callback function like this
if(sort === "newest") {
setFilteredProducts((prevState) => {
[...prevState].sort((a, b) => a.createdAt - b.createdAt)
});
}
, it is just throwing error in console.