Getter with api call if value doesn't exist already

vuex

#1

Hey,

I want to create a getter where it checks if a value != (null | undefined) and returns that value if it’s there but otherwise dispatches an api call and stores and returns the returned value.

Now, it seems this isn’t really the right pattern in vuex since getters aren’t meant to be async(for the possible api call) and can’t dispatch an action anyway.

What would be the right pattern to keep these actions opaque for the components( they just keep using a computed getter)?


#2

As you have mentioned, getters are not responsible for initialising the state, so using the access of a getter for the first time as a signal to load the data is not the correct pattern for Vuex.

Presumably there is some component outside of the store which needs that piece of data, that component should dispatch the action to ensure that data has been loaded. The action can decide whether it needs to call an API or whether the data is already loaded.

The component then simply binds to the getter, so it will either have a value or a value will shortly follow.