reactjsreact-state

Implementing undo/redo function in react


I am trying to implement simple undo/redo function in my react app. So I am trying to maintain an array with old state values. But when I check the values of the old states, its all updated with the new state.

state :

state = {
        schedule : [],
        loads:[],
        undo:[],
        redo:[]
    };

const redoUndoObj ={
        oldStateSchedule : [...this.state.schedule],
        oldStateLoads : [...this.state.loads]
  }
       
  this.setState({ undo : [ ...this.state.undo , redoUndoObj]});

Solution

  • I hope this give you an idea on how to solve the problem. I made code only for undo now to point you in the right direction. This example I made via React functional component using useState instead of Component class.

        const [schedule, setSchedule] = useState([]);
        const [loads, setLoads] = useState([]);
        const [undo, setUndo] = useState([]);
        const [redo, setRedo] = useState([]);
    
        const updateData = (newSchedule, newLoads) => {
        setSchedule([...newSchedule]);
        setLoads([...newLoads]);
    
        const newUndo = {
          schedule: [...newSchedule],
          loads: [...newLoads],
        };
    
        setUndo([...undo, ...newUndo]);
      }
    
      const undoChanges = () => {
        const lastElement = undo[undo.length - 1];
        const copyOfUndo = [...undo];
        
        // Update redo to be able to rollback
        setRedo([...undo]);
    
        // Set the previous values to Schedule and Loads
        schedule([...lastElement.schedule]);
        loads([...lastElement.loads]);
    
        // Remove the last element from undo
        lastElement.pop();
        undo([...lastElement]);
      }