Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

85
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda