John Ashmore
John Ashmore

Reputation: 1045

Unable to remove object from array without messing it up

Data Change After Hitting Delete Button

I am simply trying to remove an object from an array stored in local storage and then refresh on screen but the array messes up each time as per the image above.

Code is saved and recovered elsewhere OK but not edited in the same way.

class Home extends Component {
constructor(props) {
    super(props);

    let notes = getLocalItem(keys.listOfItems);
    if (!notes) {notes=[];}

    this.state = {
        title: '',
        content: '',
        notes: notes
    }
}

// function to go to edit note page, but opening the relevant note to edit
editNoteClicked(clickedValue) {
    setLocalItem(keys.noteToEdit, clickedValue);
    this.props.history.push('/editnote');
}

deleteNoteClicked(clickedValue) {
    let copyOfNotes = [this.state.notes]; // make a separate copy of the array
    delete copyOfNotes[clickedValue]; // delete item in array
    this.setState({ notes: copyOfNotes }, setLocalItem(keys.listOfItems, copyOfNotes)); // 


    //refresh page here
}

renderRows() {
    let rows = [];

    for (let i = 0; i < this.state.notes.length; i++) {
        let currentNote = this.state.notes[i];
        rows.push(
            <div>{currentNote.title} - {currentNote.content}
                <button className="btn" onClick={() => this.editNoteClicked(i)}>EDIT</button>
                <button className="btn" onClick={() => this.deleteNoteClicked(i)}>DELETE</button>
            </div>
        );
    }

    return rows;
}

Upvotes: 0

Views: 34

Answers (1)

Uddalak Das
Uddalak Das

Reputation: 121

The problem is in your deleteNoteClicked function, try the following code and see if this works :-

deleteNoteClicked(clickedValue) {
    let copyOfNotes = [...this.state.notes]; // make a separate copy of the array
    copyOfNotes.splice(clickedValue, 1) // Remove item at position clickedValue
    this.setState({ notes: copyOfNotes }, setLocalItem(keys.listOfItems, copyOfNotes));
}

Upvotes: 2

Related Questions