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

124
Visualizações
DOM still shows items which are have already been deleted from state in React using hooks

I am using react-dnd (Drag and Drop) to drop in items into a div which acts as a canvas for holding the items. Since I was having trouble with dnd not updating the reference of the canvas state, I had to use an useRef hook to manually update the same.

const [canvas, setCanvas] = useState([])
const canvasRef = useRef(null);

//Function to update the referrence
const _setCanvas = (Canvas) => {
    canvasRef.current = Canvas;
    setCanvas(Canvas);
};


const [{ isOver }, drop] = useDrop(() => ({
    accept: "formElement",
    drop: (item) => {
        addElementToCanvas(item.id, generateUUID());
    },
    collect: (monitor) => ({
        isOver: !!monitor.isOver(),
    }),
}));

//Function to add element on to the canvas
const addElementToCanvas = (id, uuid) => {
    const formElement = formElements.find((element) => id === element.id);
    //Add up the necessary details required for the element
    formElement.question = "Type your question here";
    if (!formElement) {
        return;
    }
    if (canvasRef.current === null) {
        canvasRef.current = [];
    }
    const formAreaElements = [...canvasRef.current, { ...formElement, uuid: uuid }];        
    _setCanvas(formAreaElements);
    setfilled(true);
};
const removeElementfromCanvas = (formElement) => {
    const updatedForm = canvas.filter((element) => element.uuid != formElement.uuid)
    _setCanvas(updatedForm);

};

Adding items to the canvas works fine. However while deleting a particular item by its uuid, the state is updated with the rest of the items. But on the DOM, the last item which has been added gets removed, and not the one which has already been deleted from the state.

<div
  className="bg-gray-800 w-full h-screen z-1   overflow-y-auto text-white "
  ref={drop}
>
  {filled &&
    canvasRef.current.map((element, idx) => {
      return (
        <li key={idx} className="mt-8 cursor-default  w-full ">
          <FormElementHolder
            questionNo={idx + 1}
            element={element}
            removeElement={() => removeElementfromCanvas(element)}
            canvasRef={canvasRef.current}
            _setCanvas={_setCanvas}
          />
        </li>
      );
    })}
</div>;

Thanks in advance!

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

0

Your element already has an id, it's better to use that instead.
Generally it's a bad practice to use indexes as keys and in this instance it is causing an error.
Index changes when you delete an item and therefore the dnd library can’t recall proper references.
This article is great one to check : https://dev.to/shiv1998/why-not-to-use-index-as-key-in-react-lists-practical-example-3e66

<div
  className="bg-gray-800 w-full h-screen z-1   overflow-y-auto text-white"
  ref={drop}
>
 {filled &&
 canvasRef.current.map((element, idx) => {
  return (
    <li key={element.id} className="mt-8 cursor-default  w-full ">
      <FormElementHolder
        questionNo={idx + 1}
        element={element}
        removeElement={() => removeElementfromCanvas(element)}
        canvasRef={canvasRef.current}
        _setCanvas={_setCanvas}
      />
    </li>
  );
})}
;
about 4 years ago · Juan Pablo Isaza Relatório

0

You can't reliably use indexes as keys when you're modifying the array like that. Details in this article linked from the React documentation. The problem is that on re-rendering, React thinks it can keep/reuse the DOM element for the previous thing at that index when you give it something new with that same index as its key.

You seem to have an id on the elements, so use the id as the key.

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