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

182
Visualizações
Update UI within .map() when condition changes?

I have a array posts, and a separate array favourites. I want the UI to display "Favourited: [Yes or No]" depending on if favourites includes the value from posts.

The problem is when I add to favourites the UI never updates.

I made a minimal example here: https://codesandbox.io/s/usestate-useeffect-playground-forked-n645c?file=/src/index.js I'm new to react and I feel like this should be simple - I did tons of research but I can't get it.

import React, { useState } from "react";
import ReactDOM from "react-dom";
function App() {
  return <TestPage />;
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


export default function TestPage() {
  const posts = ["1", "2", "3", "4", "5", "6"];
  const [favourites, setFavourites] = useState(["1"]);

  return (
    <>
      {posts.map((post) => (
        <div
          style={{
            "background-color": "lightblue",
            width: "300px",
            height: "60px",
            margin: "5px",
            "font-size": "20px"
          }}
          onClick={() => {
            favourites.push(post);
            setFavourites(favourites);
            alert("Added " + post + " to favourites");
          }}
        >
          {post}
          <br />
          Favourited: {favourites.includes(post) ? <>Yes</> : <>No</>}
        </div>
      ))}
    </>
  );
}

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

favourites.push(post);
setFavourites(favourites);

React states need to be immutable. .push will modify the existing array, and then when you set state react does a === comparison between the old and new states, sees that they're the same array, and so it skips rendering. Instead, you need to create a new array:

setFavourites([...favourites, post]);

It's also a good idea to use the function version of setFavorites when your new state is based on the old. This makes sure you have the latest value of the state and so eliminates the possibility a category of bugs.

setFavourites(prev => {
  return [...prev, post];
});
about 4 years ago · Juan Pablo Isaza Relatório

0

You can do this:

onClick={() => {
    setFavourites(favourites.concat([post]));
    alert("Added " + post + " to favourites");
}}
about 4 years ago · Juan Pablo Isaza Relatório

0

You need to always create a new object, and push that to the state.

If you push an object to state that is already in the state then React will ignore it, even if the object content has changed (it doesn't do a deep contents comparison).

This code will work:

onClick={() => {
    const newFavs = [favourites]; // create copy of original object
    newFavs.push(post);
    setFavourites(newFavs);
    alert("Added " + post + " to favourites");
}}
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