I'm fetching data from an API and want to achieve it via Vuex. So my users store module is holding and managing all users.
To fetch all users I have a fetch action which calls the API via Axios and passes the users array from the response to the mutation.
I have a view component at /users which renders a list of users. Within that component I call
async mounted() {
await this.fetch();
}
to initialize the store. After that, the store getter will return the users array and the list gets rendered. I know that I can also fetch one item by id via getter
getById: state => id => state.users.find(user => user.id === id)
When navigating to a user detail page /users/:id I can make use of it, extract the userId via this.$router.currentRoute.params.id and render the user details. But what if I load that route directly? Then the store initialized with an empty users array and it won't find a single user.
So should I fetch all users again in the mounted hook of that user details view? I think calling the axios service directly would be an anti pattern because the resources say I should use Vuex as an interface between the component and the API.
Is there a best practise when to fetch all users from the api? Because let's image you navigate to another page which loads all users in a select component, should I fetch them from the getter? Maybe it will load a user that doesn't exist anymore. But polling all users every X seconds would be bad too...
What is the correct way to update the store data to make it accessible for all components in the entire application?