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

91
Visualizações
Adding a new item to list in ReactJS functional Component not updating UI

I have a list as follows

const[users,setUsers]=useState([]);

to dynamically add a new user and update the UI i have a function as below

const addNewUser = newUser => {
      setUsers(previousUsers=>{
            //only add user if he has not been added
            let existingUser = previousUsers.find((x)=>x.id===newUser.id);
            if(!existingUser){
                previousUsers.push(newUser);
            }
            return previousUsers;
        });
}

Unfortunately the above code is not updating the UI. This is weird.

What could I be doing wrong?

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

0

I would do the check outside of the set state:

function addNewUser(newUser) {
  const existingUser = users.find(user => user.id === newUser.id);
  if (!existingUser) {
    setUsers(prev => ([...prev, newUser]));
  }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

The reason that the UI is not re-rendering is because state value is not changed. If you want to use arrays or objects in React State, you have to create a copy of the value before modifying it. You can find the basic example of doing it below:

const [todos, setTodos] = useState([]);
const handleAdd = (todo) => {
    const newTodos = [...todos];
    newTodos.push(todo);
    setTodos(newTodos);
}
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