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

95
Visualizações
useState / setData is not updating

I am trying to figure out a way to do filter by price and name, but somehow the useState won't update. I printed the result out and it worked on both checkboxes. By the way, is it better to use onChange or onClick on checkbox, both look the same to me. I have watched many tutorials and searched for many possible solutions but I still can't solve this problem.

let product = [
    {
      name: "tesla",
      cost: 500,
    },
    {
      name: "benz",
      cost: 1000,
    },
    {
      name: "honda",
      cost: 200,
    },

    {
      name: "apple",
      cost: 400,
    },
  ];

  const [data, setData] = useState(product);

  const sortbyprice = () => {
    const result = product.sort((a, b) => {
      return a.cost > b.cost ? 1 : -1;
    });
    setData(result);
    console.log(result);
  };

  const sortbyname = () => {
    const result = product.sort((a, b) => {
      return a.name > b.name ? 1 : -1;
    });

    setData(result);
    console.log(data);
  };

  return (
    <div className="App">
      <div className="sort price">
        <h3>Sort by price</h3>
        <input
          type="checkbox"
          className="searchbar"
          onChange={sortbyprice}
        ></input>
      </div>
      <div className="sort name">
        <h3>Sort by name</h3>
        <input
          type="checkbox"
          className="searchbar"
          onChange={sortbyname}
        ></input>
      </div>

      <div className="product-container">
        {data.map((item, index) => {
          return (
            <div className="product" key={index}>
              <h2>{item.name}</h2>
              <p>{item.cost}</p>
            </div>
          );
        })}
      </div>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I'm updating my answer in order to cover both cases where product is inside the component or outside.

The problem is the array mutation

You can read more here How can you sort an array without mutating the original array?

The correct way is the following and it should work

 const sortbyprice = () => {
    let dataClone = [...data];
    const result = dataClone.sort((a, b) => {
      return a.cost > b.cost ? 1 : -1;
    });
    setData(result);
    console.log(result);
  };

  const sortbyname = () => {
    let dataClone = [...data];
    const result = dataClone.sort((a, b) => {
      return a.name > b.name ? 1 : -1;
    });

Check this sandbox

about 4 years ago · Juan Pablo Isaza Relatório

0

You have to use two different state variables for the this check boxes, and when clicking on one of these you have to update your state accordingly here is CodesandBox.

Edit awesome-maxwell-wd0rz2

about 4 years ago · Juan Pablo Isaza Relatório

0

This all looks good, I run it on codesandbox and it does rerenders. But anyway I would suggest you to move product array out of the component, and just to use it as initial value for useState hook, and on state update use input parameter from setData callback - eg: setData(prev => [...prev.sort(...)]), no need each time to reference initial array since you already used it when calling hook in your component.

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