Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

84
Views
array wont render on React state change

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!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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!

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!