xplato / useUndoable

↪ React hook for undo/redo functionality (with batteries included)
MIT License
168 stars 7 forks source link

[question] Dirty flag #14

Closed brunoandradebr closed 1 year ago

brunoandradebr commented 2 years ago

Is there a way to know if my state is "dirty", if it's different from the initial state ?

// or maybe isModified   
const [myState, setMyState, {undo, redo, isDirty}] = useUndoable(...)
xplato commented 2 years ago

Hmm, interesting idea! While I think about the appropriate implementation, you can quickly replicate this behavior with something like:

const [initialState, setInitialState] = useState(['some initial state']);
const [state, setState, { undo, redo }] = useUndoable(initialState);

const isDirty = JSON.stringify(initialState) !== JSON.stringify(state);

Might I ask what you'd be using this for? (Just to get an idea of your use case, which my implementation may consider).

brunoandradebr commented 2 years ago

yeah. this is how i'm doing. I'm using with reactflow. I need to indicate when there was canvas modification.

xplato commented 2 years ago

Nice, okay. I will update you when this option has been added.

xplato commented 1 year ago

Upon further analysis (and forgive my horrid delay here), I've decided not to implement this; I think there's too many conditions to be added here. For example, some projects may store a single string, which is easy to compare, but others may store very complicated, deeply-nested objects, which are more difficult to compare. I think this should be done on a per-project basis.

I do truly thank you for your suggestion, @brunoandradebr! It's awesome to hear of improvements people want to see. Unfortunately, I think this one is a little too far removed from the focus of this project 👍

Best wishes!

brunoandradebr commented 1 year ago

I got time to answer you back, sorry for late response. BUT if you could still consider this feature to your lib this could be a universal solution:


const listA = {
         bla: 'bla-string',
         properties: [
            {
               name: 'foo',
               type: 'string',
            },
            {
               name: 'bar',
               type: 'number',
               properties: [
                  {
                     name: 'bruno',
                     type: 'noop',
                  },
               ],
            },
         ],
      }

const listB = {
         bla: 'bla-string',
         properties: [
            {
               name: 'foo',
               type: 'string',
            },
            {
               name: 'bar',
               type: 'number',
               properties: [
                  {
                     name: 'bruno',
                     type: 'noop',
                  },
               ],
            },
         ],
      }

 const A = btoa(JSON.stringify(listA))
 const B = btoa(JSON.stringify(listB))
 console.log(A === B) // true