@stackoverfloweth/vue-compositions
Version:
A collection of reusable vue compositions.
47 lines • 2.17 kB
JavaScript
import isEqual from 'lodash.isequal';
import { reactive, ref, toRaw, watch } from 'vue';
import { useSubscription } from '../useSubscription/useSubscription';
const voidAction = () => undefined;
// returns a void subscription with executed overridden to be false
function rawVoidSubscription() {
const subscription = toRawSubscription(useSubscription(voidAction));
subscription.executed = ref(false);
return subscription;
}
// toRaw doesn't get the original type so this utility correctly sets the type to a MappedSubscription
// which is the type useSubscription returns wrapped in reactive()
function toRawSubscription(subscription) {
return toRaw(subscription);
}
/**
* Similar to `useSubscription` but delays executing the action if args is null.
*
* This is useful for when you want to use a subscription but the arguments are not available yet (e.g. the result of a promise).
* A common use case is for chaining subscriptions so that the second subscription is only executed after the first one is done.
*
* @see [`useSubscription`](https://github.com/PrefectHQ/vue-compositions/tree/main/src/useSubscription#readme) for more details.
*/
export function useSubscriptionWithDependencies(...[action, args, options = {}]) {
const subscription = reactive(rawVoidSubscription());
watch(args, (value, previousValue) => {
if (value === null && previousValue === undefined) {
return;
}
if (isEqual(value, previousValue)) {
return;
}
if (subscription.isSubscribed()) {
subscription.unsubscribe();
}
if (value === null) {
Object.assign(subscription, rawVoidSubscription());
return;
}
const newSubscription = toRawSubscription(useSubscription(action, args, options));
newSubscription.response.value ??= subscription.response;
newSubscription.executed.value = newSubscription.executed.value || subscription.executed;
Object.assign(subscription, newSubscription);
}, { deep: true, immediate: true });
return subscription;
}
//# sourceMappingURL=useSubscriptionWithDependencies.js.map