We'll move this into the store by simply cutting it out, also deleting the Axios dependency, and creating an index file in the store called index.js. We'll just start with a state. We'll export const state, and this is a function which returns an object. We'll call this users.
We'll just make a users array with one object with an ID of zero and a login of John, just to show this working. Then we can access this in our index page by importing from Vuex a helper called mapState. Then we take the computed property in our exported object.
We set it to mapState, and pass in an array of the values we want off the state. Right now, we want the users. Computed doesn't access the data directly. It lets you pass in a method. What we're passing in is mapState, which knows about the store.
Based on the keys you pass in, it will map for the store this users to the users property in this index page. I'll go ahead and run this, NPM run dev. You can see that the only user here is John, because in the store, the only user is John.
To load the data, we'll need a couple more things. We'll need mutations, which is an object, and we'll need actions, which is an object. We'll start with actions, and the method called nextServerInit. This will trigger when the server initializes, and we can tell it to load the data.
I'll go ahead and import Axios from plugins/axios, like we did before. Then I'm going to write this in the async await way. We'll call nextServerInitAsync, what we'll await for axiosGetUsers. This can be the response.
I'll close the sidebar for some more room, then I'll want the users as the response.data. Then I do what's called committing. That's by taking off the...This is a context, and I only need the commit method off of that context.
I'll use that to say setUsers, and then I'll just pass in the users. What this does is triggers something in mutations. Let's add setUsers. This commit is calling this setUsers here, and setUsers takes the state and the users. All it has to do here is say state.users equals users.
Now when I save, you'll see the initial loaded data was the list of GitHub users. Even though I set this as the initial data, this next serverInit ran and committed that data before this data was ever even displayed.
Then you can see in our index page, there's no reference to any sort of data loading or anything. We're just mapping the state on the store, and getting the properties we need. The one we need is called users, which are loaded here, committed here, assigned and updated here.