title |
---|
Common Patterns |
If you have a "WTF this isn't working" moment while setting up a new service, make sure you've set the idField
property on your service. In feathers-vuex@1.x
, the id
is the default idField
. You have to manually set _id
. Starting in feathers-vuex@2.x
, both the id
and _id
fields are supported without any configuration, so you only set the idField
when your service uses something else.
You can set debug: true
in the options to enable some logging to assist with debugging.
Using the new <FeathersVuexFind>
and <FeathersVuexGet>
components provides concise access to the best features of feathers-vuex
, including live queries, reactive lists, custom pagination tracking per component, and fall-through cacheing of local data in the Vuex store. Check out the Renderless Data Components docs for more details.
The mixin utilities provide the same functionality as the components, but with more power and flexibility. Check out the Mixin docs for more details.
As of version 2.0, Feathers-Vuex has been rewritten in TypeScript.
See this issue for suggestions for with TypeScript helpers.
The best solution is to simply refresh to clear memory. The alternative to refreshing would be to perform manual cleanup of the service stores. Refreshing is much simpler, so it's the officially supported solution. Feel free to read this issue for more suggestions.
Because the service's Model is available at service.FeathersVuexModel
, you can access the store inside hooks. This is especially handy if you have some custom attributes in a paginated server response.
As an example, this speeding-tickets
service has a summary
attribute that comes back in the response. We can
import { makeServicePlugin, BaseModel } from '../feathers-client'
class SpeedingTicket extends BaseModel {
constructor(data, options) {
super(data, options)
}
// Required for $FeathersVuex plugin to work after production transpile.
static modelName = 'SpeedingTicket'
// Define default properties here
static instanceDefaults() {
return {
vin: '',
plateState: ''
}
}
}
const servicePath = 'speeding-tickets'
const servicePlugin = makeServicePlugin({
Model: SpeedingTicket,
service: feathersClient.service(servicePath),
servicePath,
mutations: {
handleSummaryData (state, summaryData) {
state.mostRecentSummary = summaryData
}
}
})
feathersClient.service(servicePath)
.hooks({
after: {
find: [
context => {
const { service, result } = context
if (result.summary) {
service.FeathersVuexModel.store.commit('handleSummaryData', result.summary)
}
}
]
}
})
Sometimes your server response may contain more attributes than just database records and pagination data. You could handle this directly in a component, if it's only needed in that one component, But, if you need it in multiple components, there are better options.
Depending on what you need to do, you may be able to solve this by accessing the store from hooks. But that solution won't handle a scenario where you need the response data to be already populated in the store.
If you need the response data to already be in the store, you can use the afterFind
action. Here's what this looks like:
import { makeServicePlugin, BaseModel } from '../feathers-client'
class SpeedingTicket extends BaseModel {
constructor(data, options) {
super(data, options)
}
// Required for $FeathersVuex plugin to work after production transpile.
static modelName = 'SpeedingTicket'
// Define default properties here
static instanceDefaults() {
return {
vin: '',
plateState: ''
}
}
}
const servicePath = 'speeding-tickets'
const servicePlugin = makeServicePlugin({
Model: SpeedingTicket,
service: feathersClient.service(servicePath),
servicePath,
actions: {
afterFind ({ commit, dispatch, getters, state }, response) {
if (response.summary) {
commit('handleSummaryData', response.summary)
}
}
},
mutations: {
handleSummaryData (state, summaryData) {
state.mostRecentSummary = summaryData
}
}
})
Using Live Queries will greatly simplify app development. The find
getter enables this feature. Here is how you might setup a component to take advantage of them. The next example shows how to setup two live-query lists using two getters.
import { mapState, mapGetters, mapActions } from 'vuex'
export default {
name: 'some-component',
computed: {
...mapState('appointments', { areAppointmentsLoading: 'isFindPending' }),
...mapGetters('appointments', { findAppointmentsInStore: 'find' } ),
// Query for future appointments
queryUpcoming () {
return { date: { $gt: new Date() }}
},
// Query for past appointments
queryPast () {
return { date: { $lt: new Date() }}
},
// The list of upcoming appointments.
upcomingAppointments () {
return this.findAppointmentsInStore({ query: this.queryUpcoming }).data
},
// The list of past appointments
pastAppointments () {
return this.findAppointmentsInStore({ query: this.queryPast }).data
}
},
methods: {
...mapActions('appointments', { findAppointments: 'find' })
},
created () {
// Find all appointments. We'll use the getters to separate them.
this.findAppointments({ query: {} })
}
}
in the above example of component code, the upcomingAppointments
and pastAppointments
will automatically update. If a new item is sent from the server, it will get added to one of the lists, automatically. feathers-vuex
listens to socket events automatically, so you don't have to manually wire any of this up!
You can use the file system to organize each service into its own module. This is especially useful in organizing larger-sized projects. Here's an example store.js
. It uses Webpack's require.context feature save repetitive imports:
import Vue from 'vue'
import Vuex from 'vuex'
import { FeathersVuex } from '../feathers-client'
import auth from './store.auth'
Vue.use(Vuex)
Vue.use(FeathersVuex)
const requireModule = require.context(
// The path where the service modules live
'./services',
// Whether to look in subfolders
false,
// Only include .js files (prevents duplicate imports`)
/.js$/
)
const servicePlugins = requireModule
.keys()
.map(modulePath => requireModule(modulePath).default)
export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
plugins: [...servicePlugins, auth]
})
With the store.js
file in place, we can start adding services to the services
folder.
- Learn how to setup a Vuex plugin for a Feathers service.
- Learn how to setup the feathers-client.js file
- Learn how to setup the auth plugin
Previously, when you directly used the response from an action, the individual records were not reactive. This meant that these plain objects wouldn't update when you updated the matching record in the store.
methods: {
...mapActions('todos', { findTodos: 'find' })
},
created () {
this.findTodos({ query: {} })
.then(response => {
const todos = response.data || response
// Suppose firstTodo has an id of 'todo-1'
const firstTodo = todos[0]
// Now, when you update the data in the store...
this.$store.state.todos.keyedById['todo-1'].description = 'Updated description'
// ... the instance in the `find` response also updates. Yay!
console.log(firstTodo.description) // --> 'Updated description'
})
}
This is a super convenient feature, and it works with all actions (except remove, of course) But be aware that only the individual records returned are reactive. The lists, themselves, are not reactive. So if another record comes in from the server that matches the query, the list will not update. For reactive lists, you must use the find
getter, as shown in the following example.
computed: {
...mapGetters('todos', { findTodosInStore: 'find' })
todos () {
return this.findTodosInStore({ query: {} }).data
}
},
methods: {
...mapActions('todos', { findTodos: 'find' })
},
created () {
this.findTodos({ query: {} })
.then(response => {
// In the find action, the 'todos' array is not a reactive list, but the individual records are.
const todos = response.data || response
})
}
In the above example, the computed todos
will be a reactive list. This means that when new records are added to the store, the list of todos will automatically update in the UI to include the new data.
In summary, you can plan on individual records in the action response data to be reactive, but if you need the actual arrays to be reactive to live queries, use the 'find' getter.
See the instanceDefaults API
You may find yourself in a position where model-specific computed properties would be very useful. github issue. In Feathers-Vuex 1.7, these could be specified in the instanceDefaults
. As of 2.0, they are specified directly on each Model class:
class Post extends BaseModel {
// Required for $FeathersVuex plugin to work after production transpile.
static modelName = 'Post'
// Define default properties here
static instanceDefaults() {
return {
description: '',
isComplete: false,
comments: [],
}
}
// Specify computed properties as regular class properties
get numberOfCommenters () {
// Put your logic here.
},
set someOtherProp () {
// Setters also work
}
}
A common task with almost any API is properly handling relationships between endpoints. Imagine an API where you have /todos
and /users
services. Each todo record can belong to a single user, so a todo has a userId
.
// GET todos/1
{
id: 1,
description: 'Learn about the health benefits of a low-carb diet.',
isComplete: false,
userId: 5
}
And a user response looks like this:
// GET users/5
{
id: 5,
name: 'Marshall',
username: 'marshallswain'
email: 'marshall@ilovehealthy.com'
}
Suppose a requirement is put on the /todos
service to populate the user
in the response. (As a super handy side note, this task is pretty easy when using Matt Chaffe's magical, efficient feathers-shallow-populate hook) So now the todo response looks like this:
{
id: 1,
description: 'Learn about the health benefits of a low-carb diet.',
isComplete: false,
userId: 5,
user: {
id: 5,
name: 'Marshall',
username: 'marshallswain'
email: 'marshall@ilovehealthy.com'
}
}
Can you see the problem that will occur with this response? When this record is put into the /todos
store, it will contain a copy of the user record. But we already have the user record in the /users
store. And what happens when the user data changes? Now it's out of sync. To keep it in sync, you might have to manually listen for users updated
& users patched
events. Then you might have to write a custom mutation to update the user record attached to every applicable todo
record. This gets messy, fast!
There's an easier way to solve this problem. Use the new setupInstance
method on Model classes.
import feathersClient, { makeServicePlugin, BaseModel } from '../feathers-client'
class Todo extends BaseModel {
// Required for $FeathersVuex plugin to work after production transpile.
static modelName = 'Todo'
// Define default properties here
static instanceDefaults() {
return {
email: '',
password: ''
}
}
// Updates `data.user` to be an instance of the `User` class.
static setupInstance(data, { models }) {
if (data.user) {
data.user = new models.api.User(data.user)
}
return data
}
}
const servicePath = 'todos'
const servicePlugin = makeServicePlugin({
Model: Todo,
service: feathersClient.service(servicePath),
servicePath
})
When this record is instantiated, the user
attribute will first be turned into a User model instance, stored properly in the /users
store. The todo.user
attribute will be a reference to that user. No more duplicate data! Here's an example of how to set this up.
There's another amazing benefit from these relationships. Because feathers-vuex
listens to real-time events and keeps data up to date, when the user record changes, the todo.user
automatically updates!
Use the Model classes to reduce the boilerplate required to work with forms and Vuex, even in strict mode! Every model instance has a .clone()
method which can be used to get a fully-reactive copy of the record in the store. Here is a very simple version of how you could bind to a form and submit new data to the server.
<template>
<div class="bg-white h-full p-6">
<h1>Create Todo</h1>
<form @submit.prevent="createTodo">
<input v-model="clone.name" type="text" class="form-input" />
<button
type="submit"
class="bg-blue-500 px-4 py-2 rounded text-white ml-2"
>
Create Todo
</button>
</form>
</div>
</template>
<script>
export default {
name: 'Todos',
mixins: [makeFindMixin({ service: 'todos', watch: true })],
data: () => ({
todo: null,
clone: null
}),
computed: {
todosParams() {
return {
query: {},
paginate: false
}
}
},
created() {
const { Todo } = this.$FeathersVuex.myApi
this.todo = new Todo({})
this.clone = this.todo.clone()
},
methods: {
async createTodo() {
try {
const todo = await this.clone.save()
console.log(todo)
} catch (error) {
console.log(error)
}
},
updateTodo(ev, todo) {
todo.isComplete = ev.target.checked
todo.save()
}
}
}
</script>
<style lang="postcss"></style>
The previous version of feathers-vuex
was hard-coded to allow for a single current
record and one copy. It was pretty easy to hit that limit. This new release allows for keeping many more copies, one copy per stored record. To make it easier to comply with Vuex's strict
mode, copies are not kept in the store by default, but are instead kept on Model.copiesById
. You can make changes to the copies without having to make custom mutations, then you can commit them back into the store:
const { Todo } = this.$FeathersVuex
// Create two records in the store (since they have ids, they get stored)
const todo = new Todo({ id: 1, description: 'Become more aware of others.'})
const todo2 = new Todo({ id: 2, description: 'Heal one ailments through healthy eating.'})
// Create a deep-cloned copies in Todo.copiesById
const todoCopy = todo.clone()
const todoCopy2 = todo2.clone()
// Try to clone a copy, and fail.
todoCopy.clone() // --> Error: You cannot clone a copy.
todoCopy2.clone() // --> Error: You cannot clone a copy.
// Modify the copies.
todoCopy.description.replace('others', 'self')
todoCopy2.description.replace('one', 'all')
// and update the original records
todoCopy.commit()
todoCopy2.commit()
You can use the keepCopiesInStore
option to make this service keep all of its copies in state.copiesById
. Remember that to comply with Vuex strict
mode (if that's a concern for you), you'll have to write custom mutations. If it's not a concern (maybe you're the sole developer or whatever reason), you could technically turn off strict
mode, enable keepCopiesInStore
, and modify them however you desire, ignoring custom mutations.
import Vue from 'vue'
import Vuex from 'vuex'
import feathersVuex from 'feathers-vuex'
import feathersClient from './feathers-client'
const { service, auth, FeathersVuex } = feathersVuex(feathersClient, { idField: '_id' })
Vue.use(FeathersVuex)
Vue.use(Vuex)
export default new Vuex.Store({
plugins: [
service('todos', {
keepCopiesInStore: true,
instanceDefaults: {
description: '',
complete: false
}
})
]
})
If items aren't not getting added to the store properly, try setting the debug
option on the makeServicePlugin
to true
. It enables some additional logging that may be useful for troubleshooting.