Home > Net >  array wont render on React state change
array wont render on React state change

Time:08-22

I have this useState hook:

    const [products, setProducts] = useState([])

and I have these functions:

    const sortByLow =()=>{
    const newArray = products.sort((a,b)=>b.price-a.price)
    setProducts(newArray)    
    console.log(newArray);    
}
const sortByHigh =()=>{
    const newArray = products.sort((a,b)=>a.price-b.price)
    setProducts(newArray) 
    console.log(newArray);
}

a useEffect hook:

    useEffect(()=>{
    const displayProducts = async()=>{
        try {
            //fetch from server at port 3000
            const response = await fetch('http://localhost:3000/')
            if(!response.ok){
                throw new Error("displayProducts response is not ok")
            }
            
            const responseDataObject = await response.json()                
            const allProducts = responseDataObject.data.allProducts
            setProducts(allProducts);
        } catch (error) {
            console.log("theres an error"   error);
        }
    }
    //call the function, duh
    displayProducts();
    
}, [])

and the return value of the component is this:

 <div>
        {products.filter( product => {return (product.price > lowPrice && product.price < highPrice)} ).map(productObj => <ProductComponent 
        navigateToProduct = {productObj._id}
        navigateToCategory = {productObj.category}
        key = {productObj._id}
        name = {productObj.name}
        category = {productObj.category}
        price = {productObj.price}
        description = {productObj.description}
        image = {productObj.image}            
        />)}
    </div>

now I expect the product array to change according to the functions above but it wont happen for some reason. what can be the problem? please help me thanks!

CodePudding user response:

ok I figured it out thanks to @KonradLinkowski comment... The sort only references the original array, so in order to create a new array I should have written [...products] as the source array, as follows:

    const sortByLow =()=>{
    const newArray = [...products].sort((a,b)=>b.price-a.price)
    setProducts(newArray)    
    console.log(newArray);    
}
const sortByHigh =()=>{
    const newArray = [...products].sort((a,b)=>a.price-b.price)
    setProducts(newArray) 
    console.log(newArray);
}   

Thanks to all who read and helped!

CodePudding user response:

When you sort through an array it does not make a new reference ID so it does not know to update the state. This is how you can force it to make a new reference

  const sortByLow = () => {
    const newArray = [...products];
    newArray.sort((a, b) => b.price - a.price);
    setProducts(newArray);
    console.log(newArray);
  };
  const sortByHigh = () => {
    const newArray = [...products];
    newArray.sort((a, b) => a.price - b.price);
    setProducts(newArray);
    console.log(newArray);
  };

This should update the react state

  • Related