laracasts / Vue-Forms

https://laracasts.com/series/learn-vue-2-step-by-step/episodes/19
396 stars 204 forks source link

Form resets to initial data, which is weird after record has been updated #13

Open dschreij opened 7 years ago

dschreij commented 7 years ago

I am experiencing some weird behaviour when updating an existing record:

Once the updated information has been persisted in the database, the onsuccess() method in axios's then() method is fired. In this function, the this.reset() function is always called, which restores the form to its state of before the update; thus when it contained the old information that has just been changed/updated. There is currently no way to opt-out of this form reset, but would it be possible to make this? Maybe leave this action to the user to call it in the promise that is returned to the form?

mtchuenten commented 5 years ago

I had the same issue today, and I ended up modifying the Form.js file in a few places. Without claiming this is the best way to go about this, I believe it sorts out what you described.

  1. Modify the submit method to also pass the requestType on success:

    submit(requestType, url) {
        return new Promise((resolve, reject) => {
            axios[requestType](url, this.data())
                .then(response => {
                    this.onSuccess(response.data, requestType);
    
                    resolve(response.data);
                })
                .catch(error => {
                    this.onFail(error.response.data.errors);
    
                    reject(error.response.data.errors);
                });
        });
    }
  2. Modify the onSuccess method to call different methods based on requestType:

    onSuccess(data, requestType) {
        if(requestType == 'put' || requestType == 'patch')
            this.resetOriginalData();
        else
            this.reset();
    }
  3. Create the new method:

    /**
     * Reset the originalData fields. The is needed after an update ('put' or 'patch' request)
     */
    resetOriginalData() {
        for (let field in this.originalData) {
            this.originalData[field] = this[field];
        }
    
        this.errors.clear();
    }
  4. The reset method remains unchanged:

    /**
     * Reset the form fields.
     */
    reset() {
        for (let field in this.originalData) {
            this[field] = this.originalData[field];
        }
    
        this.errors.clear();
    } 

Good luck! I hope it helps.