[Vuejs]-Vuex action changes component data

2đź‘Ť

âś…

why is the action executed twice

You have two event listeners attached on the form:

  1. @submit.prevent
  2. @keyup.enter

The event handler for both these event is submit( form ) which is dispatching the action

When you are focused in an input field and hit the enter button then the form will be submitted implicitly.
Therefore the submit( form ) will be called twice ;

  1. Form’s submit method being called
  2. Since the enter button is pressed the event handler for @keyup.enter is also called

Why does the password field value change when the value is only “stored and read” from within the component?

You are passing the form as payload to the action which is an object:

form: { email: '', password: '', }

In JavaScript objects are passed by reference.
In your action you are mutation the form object’s password property by

data.password = btoa( data.password );

So the changes are reflected in the component also

———————————-

SOLITION

why is the action executed twice

Since the default behavior of hitting enter when an input is in focus is submitting the form you can remove @keyup.enter listener

Why does the password field value change when the value is only "stored and read" from within the component?

Do not mutate the original object. Instead create a new one and pass that as your post request body

// Base64 encode password
let details = {
        email: data.email, 
        password: btoa( data.password )
    }

fetch( '/api/users/login', {
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-token': window.token,
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    },
    method: 'POST',
    body: JSON.stringify( details )
})
👤Vamsi Krishna

Leave a comment