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

195
Visualizações
React updating state creates duplicate element in DOM but state updates correctly

I have a component with a method to add/create a new sub-component and insert it into an array at a specific index (i.e. [elem1, elem2, elem3] becomes [elem1, elem2, new elem, elem3]).

When using something like array.splice(currentIndex + 1, 0, newElement), in the DOM the last element that already exists is just duplicated, though it appears to update correctly for the array in state.

The only way I have found that works is to just use array.push(newElement), which does render properly but is not the desired effect. I've tried a few more ways of inserting the new element into the array but so far everything other than .push() causes the duplication issue. Any suggestions or tips would be greatly appreciated!

    const Notef = ({ fetchedParts }) => {

    const [parts, setParts] = useState(fetchedParts);

    const addNewPart = (currentPart) => {
        const index = parts.map((p) => p.id).indexOf(currentPart.id);
        const updatedParts = [...parts];
        const newPart = { id: pid(), html: 'Type here...', tag: 'p' }
        // This will cause duplicated element
        updatedParts.splice(index + 1, 0, newPart);
        // This does not create duplicate
        //updatedParts.push(newPart);
        setParts(updatedParts);
    }

    return (
        <> 
            {parts.map((part) => {
                const position =  parts.map((p) => p.id).indexOf(part.id) + 1;
                return (
                    <Part
                        key={part.id}
                        position={position}
                        id={part.id}
                        tag={part.tag}
                        html={part.html}
                        addPart={addNewPart}
                    />
                );
            })}
        </>
    );
}

export default Notef;

Element duplication w/ .splice()

Element addition w/ .push()

edit: re-worded intro to specify new element to be inserted rather than replaced.

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

0

Dominic found the issue - I was using indices for keys in the rendered component. Replaced that with the ID and it solved the issue!

return (
    <> 
        {parts.map((part) => {
            const position =  parts.map((p) => p.id).indexOf(part.id) + 1;
            return (
                <Part
                    key={part.id}
                    position={position}
                    id={part.id}
                    tag={part.tag}
                    html={part.html}
                    addPart={addNewPart}
                />
            );
        })}
    </>
);
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