Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

95
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda