Search code examples
vue.jsvuedraggable

Vue watcher restore old values?


im using this component to make a list of sortable items. https://sortablejs.github.io/Vue.Draggable/#/simple

I have one array with the items in my view component data. Then i use an v-for to pain the list, one row for each item in my array.

So everytime i move one item, the array of items gets sorted and change the order of the array items, thats the behaviour of this component.

But i have to make a post call to an api to save the new order fot the list. So i defined a watcher over the array of items, and everytime it gets sorted by the draggable component, i make the request to the api if the array order has changed.

The problem comes when this request fails, i want to restore the old values in the view, so i dont have one order in the view an another different stored in database.

Inside my watcher i have prevValues and newValues, that i use to compare and check if there is any change in the items order, then make the request, and then, if the request fails, restore the datavalue with the prevValues array.

The problem is that could get to an infinite loop, because when i restore the old values, the watcher over the original array is triggered again, make the request, fails, restore values and so on.

Is there any way to restore old values passed to a watcher without triggering the watcher again?

Thank you


Solution

  • It would be more reliable to react to drag events to trigger your API calls, rather than watching the data. That way your code only does work in response to user action.

    Alternatively, stash a copy of the original array and use something like deep-equal to compare it to the latest value to determine if changed before making a call.