Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the 'proper' way to bind Vue state data to a database?

Tags:

vue.js

vuex

At the moment, if a user causes an action that edits data, I send the API call off and then just effectively do a 'refresh' command to my app that re-downloads all the relevant data from the database, and the view updates accordingly.

Should I instead be directly editing data in my Vuex state, and have some sort of watcher function that observes those changes and writes them back to the DB?

like image 374
daninthemix Avatar asked Oct 29 '22 16:10

daninthemix


1 Answers

I wouldn't start by editing the data directly in Vuex as that may not then accurately represent the current state of your database, which could get very awkward...

Instead I would create an API module within your app that returns a Promise which makes the required updates to your database. Then on the success / error response coming from your database's API you resolve / reject the Promise. On success the resolve callback can pass the updated data.

Therefore on an edit the vue API is called, which sends the request and data to your database endpoint. The vue API returns a promise which you then chain to update your Vuex state. On success you receive an object containing the updated data, on error you get the message and alert the user if required, i.e.

# Your Vue API
setUserName: (username) => new Promise((resolve, reject) => {

  // send request to your database, assuming via vue resource
  Vue.http.post('www.endpoint.com', { name: username })
    .then(responseData => resolve(responseData.name))
    .catch(errorData => reject(errorData))

}

# Your Vuex Action
updateUserName: ({ commit }) => {

  YourVueAPI.setUserName('joe')
    .then(name => commit('SET_USERNAME', name))
    .catch(errorData => alert(errorData.message))

}

# Your Vuex Mutation
SET_USERNAME: (state, name) {

  state.username = name

}

Something like the above will allow you to only show the updated username when it is correctly set within your database. Therefore ensuring the user is always aware of the correct state of the DB.

Vue will then allow you to easily react/watch the Vuex state to update your page.

like image 200
GuyC Avatar answered Nov 09 '22 02:11

GuyC