Home > Enterprise >  Vue: Reset data object to original value after API call has failed
Vue: Reset data object to original value after API call has failed

Time:09-25

I have a Vue component which fetches data from a remote API passing it to a child component. When the user clicks a button, the API is called to submit the data. The API returns the updated data object and updates the component with the new data. So far, so good.

But I'm struggling for the error case. If the API call is not successful, I need to "reset" the apiData object to the initial state as received in the mounted() function. Otherwise the user would still see the values she changed but which actually failed to update.

Two apporaches come to my mind:

  1. Refresh the data from the API for the error case
  2. Copy the originally received data to a variable which then will be re-assigned in the error case

Or maybe there is some more "Vue-ish" way to achieve this?

<template>
    <some-component v-model="apiData"></some-component>
</template>
data() {
    return {        
        apiData: {}
    }
},
mounted() {
   this.apiData = ApiService.getData();
},
methods: {
    async onSubmit() {
        try {
            const response = await ApiService.update(this.apiData);
            this.apiData = response.data;
        } catch (e) {
            showErrorNotification();
            // How to reset `apiData` to the initial state as in mounted() ???
        }     
    }
}

CodePudding user response:

The API gets an error and does not return us any new results. If it doesn't return new results, we still have our old data (the data you want) Aren't we waiting for this? If so, what's the problem for us?

  • Related