Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

83
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda