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

94
Visualizações
Automatically select next item in array

I have a button that deletes a note, and it is supposed to automatically select the next note after the first note is deleted. However, it is not working, and i have this error Uncaught TypeError: Cannot set properties of undefined (setting 'selected')

import React, { useContext } from 'react';
import trashicon from '../../trashicon.png'
import {NoteContext} from '../../noteContext';

const DeleteNote = () => {
    const [notes, setNotes] = useContext(NoteContext);

    const handleDeleteNote =()=> {
        const newNotesList = notes.filter(itemChecked=>itemChecked.selected===false)
        console.log(newNotesList[0])
        for (let i = 0; i < notes.length; i++) {
            if(notes[i].selected === true) {
                newNotesList[i].selected = true;
            }
        
        }
        console.log(newNotesList);
        setNotes(newNotesList);

    }
    return (

            <img src={trashicon} className="delete-icon" onClick={handleDeleteNote}/>

    )
}
export default DeleteNote
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This logic is quite incorrect, what if notes arr has 5 objects, and newNotesList returns 3 different objects, then when you loop it will update first 3 incorrect objects in the newNotesList array.

IMO, this should be the correct logic.

if (!newNotesList.length) return;
for (let i = 0; i < notes.length; i++) {
    //
}

if(notes[i].selected === true) {
    const findElementInNewNotesList = newNotesList.find(el => el.id === notes[i].id);
    if(findElementInNewNotesList.id) newNotesList[i].selected = true;
}

This way you're finding the matching object ONLY from newNotesList.

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