[SOLVED] Using prevState Callback function in UseState react Hook

Issue

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.

Solution

When using the brackets you are declaring a function body, and need to return a value, i.e. the next state. Arrow functions without a function body use an implicit (vs explicit) return.

setFilteredProducts((prevState) => {
  return [...prevState].sort((a, b) => a.createdAt - b.createdAt);
});

Answered By – Drew Reese

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *