Adding some mutations to our store

One important thing to know about Vuex is that, even though the global state is accessible from any of our components, we should not directly mutate or modify it. To modify the content of our user, we will need to create something called mutations. Mutations are methods that have one single job: to accept a value or payload and to commit a modification to the state. That way, Vuex can keep tabs on which components are making modifications to the state without it becoming highly chaotic!

Let's create our first mutation; we will call it updateUser

This mutation will take two parameters: the first one is state. Every mutation will always receive the state as the first parameter; it is injected to mutations by Vuex by default. The second parameter will be the value that that mutation will get when you call it—in this case, we will call it user since that is what we will pass down to it. It is important to know that mutations cannot execute asynchronous code. Every mutation needs to be synchronous because they are making changes to our state directly.

Create a new property inside the Vuex.Store configuration called mutations and then add our following new mutation to it:

mutations: {
updateUser(state, user) {
state.user = user;
},
},

When this mutation is committed, it will update the global state by calling state.user = user with the user that we pass through it. Now, where exactly do we want to commit this new mutation?

Earlier, we set up an API endpoint to fetch our mock logged-in user. We still have to set up a call to this endpoint so that our application can use it when it starts to check whether there is a user from the API.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.100.42