Recommended strategy to sync vuex state with server

浪子不回头ぞ 提交于 2021-02-17 08:27:22

问题


Imagine this simple case. You have a Vue JS application in which users can create lists of tasks and sort them. These lists should be stored in a database by the server. Let's assume we have a ListComponent which does the bulk of the UX.

My question is, which pattern should I use to handle front-end and back-end data synchronisation?

A) Go through vuex: Store the active lists (those being shown, edited or created) in the vuex store. The ListComponent will change the store and then, the changes made to a list will be sent to the backend through an API.

B) Go directly to the server: Read and write directly from the ListComponent to the server every time a list is shown, edited or created.

If following A, what architecture should the store have? How and when should I kick a synchronisation? How can I keep track of what has changed and what has not?


回答1:


Both can be correct depending on your use case. The application I'm currently building uses both.

When to use B: Go Directly to the server Use B if the data is very important to save. In this case you may want to go directly to the server and serve up the response to verify it was committed to the DB. We use this process for Admin type changes. Note that you can also update Vuex after the server response and still use Vuex to serve up your data.

When to use A: Go Through Vuex Use A if you require faster experience, since there's no waiting for the server. You must be okay with optimistically displaying changes before actually saving. The other benefit is you can sync Vuex to localStorage. We use this for user preferences that are used to customize views. Its a poor experience to slow down the page just to wait on fetching those.

How to use A: Go through Vuex There's a couple ways to do this. Here's one pattern:

  1. Dispatch Vuex Action 1 from component
  2. Commit Vuex Mutation from Action that updates state - this is an optimistic update as you're assuming it'll go through
  3. Dispatch another Vuex Action 2 from Action 1 - This assumes you'll reuse this Action in multiple Actions, otherwise it can all go in Action 1
  4. Action 2 sends data to server
  5. Upon promise return, Action 2 commits mutation to update Vuex state
  6. Mutation needs to handle any discrepancies (or errors)

Count the cost of Vuex

Like your comment shows, its good to count the cost if you need to use Vuex at all because it does add a lot of overhead and complexity. The ideal is to write your components in such a way as to contain all interactions with one type of data (such as 'Lists') so you do not have to share state through Vuex.



来源:https://stackoverflow.com/questions/43572532/recommended-strategy-to-sync-vuex-state-with-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!