1

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]});
3
  • 1
    I'd love to see more code before I can give any good advice. Commented Nov 23, 2020 at 7:17
  • My idea is to get the last state from undo array and update the state with it, unfortunately I stuck here Commented Nov 23, 2020 at 7:23
  • Hope my answer below gives you ideas on how to solve this problem. Commented Nov 23, 2020 at 7:55

1 Answer 1

3

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]);
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.