Home > Mobile >  How to keep the history of modications of an array in React State?
How to keep the history of modications of an array in React State?

Time:04-29

I am facing some problems when I try to save the history of updates and modifications on a State. I've got a object "Journey" that contains a list of workshops (another array). When I update my list of workshops I would like to create another array containing the modifications and, at the same time, I would like to keep the previous one, so that I can always see the different versions of my list of workshops.

let idToRemove = event.currentTarget.id;
    let tempJourney = [...journey];
    for (let i = 0; i < tempJourney.length; i  ) {
        for (let j = 0; j < tempJourney[i].workshops.length; j  ) {
            if (tempJourney[i]?.workshops[j]?.id == parseInt(idToRemove)) {
                tempJourney[i].workshops.splice(j, 1);
                break;
            }
        }
    }

    setHasModification( true );
    setLastJourney(journey); // Historical version
    setJourney(tempJourney); // New version
}

enter image description here

CodePudding user response:

When you spread journey the objects are still referencing to the original.

Try this:

let tempJourney = JSON.parse(JSON.stringify(journey));
  • Related