Fetching data from vuex store, best practice

I am completely stuck on how to deal with fetching data from the vuex store in the best possible way. The way I want the application to work is as follows:

  1. When a component is mounted, check if the data exists in store
  2. If it exists, use that data
  3. If not, fetch data from API

The only problem with this is if the api data is updated after I have already fetched it to my local state. So, I am looking for some input on how to deal with this problem.

Summary: Save data in state, but also listen for updates on the api

You can’t do both. The only way for the client side to know the api has been updated is to periodically request the information, or through a system like websockets. I would just recommend having the content be updated when the page is reloaded. So basically the same but without, “if exists, use the data” part. Just always fetch the data.
Websockets aren’t a bad idea. It just seems like overkill if the content doesn’t need to be always updated.

1 Like

Another approach is to use a time stamp. If your data is pretty static, but you occasionally want to refresh it this can be a simple approach.

As Issayah said, web sockets are another approach, but more applicable for real time data so the tech debt for this doesn’t seem worthwhile if the data isn’t constantly changing.

Finally, probably the best approach would be to request the data every time you need to work with it, but use a server caching layer to vastly reduce the response time. If the request data is cached then your servers response time should be sub 100 ms.

2 Likes

How do you like the following solution:

Set an interval in the root file, and fetch something every x seconds. And in the component using the computed() property to listen for changes? It seems to be working just fine, but maybe it is very heavy performance wise.

Depends on the use case. Is this data that should be polled every x seconds? e.g. For a news or stock ticker this approach could make sense.