I am currently creating a Nuxt app, which uses an API-backend to get it's data from. Since I don't know what data is needed when the page loads, I would like to stay clear of fetching on mounted()
or explicitly fetching when I need the resource and then also accessing it but instead define getters and setters in the Nuxt/Vuex store to return the data if present or fetch if missing.
Suppose I have the following data structure(s):
(projects.json)
[
{
"id": 1,
"randomdata": "abc",
"client": 1
}
]
(clients.json)
[
{
"id": 1,
"name": "Max"
}
]
My page would look something like this:
<template>
<div
v-for="project in projects">
<p>
{{project.randomdata}}
</p>
<v-checkbox
v-bind="showClient">
Show client
</v-checkbox>
<p
v-if="showClient">
{{ clients.find(c => c.id === project.client) }}
</p>
</div>
</template>
I tried multiple places to register the getters without success:
- registering getters and setters directly in
computed
==> throws "Cannot read property '$store' of undefined", I guess this is undefined
projects: {
get: () => {this.$store.dispatch('get', {resource: 'projects'}); return this.$store.state.projects}
set: (value) => this.$store.dispatch('set', {resource: 'projects', value})
}
- getters, mutations in store; using
mapState
==> Didn't get both getters and setters configured on computed property
getters: {
plants: state => {
return get(state, 'plants', this.$axios);
}
},
mutations: {
plants(state, value) {
save('plants', state.plants, value);
},
},
- javascript getters / setters in
state
==> couldn't get axios so I could do the request as intended, also is this reactive?
state: () => ({
_plants: {},
get plants() {
return get(this, 'plants');
},
set plants(value) {
this.plants = save('plants', this._plants, value);
}
}),
All of the above assuming the appropriate methods exist and work as intended.
I assume that an object is returned from the getters, whose properties are filled once the asynchronous request finished.
I would really apprciate if anyone could point me in the right direction on how to properly define these getters and setters.
TL;DR; What is the best way to define getters and setters for API requests using Nuxt/Vuex store?