Skip to content

Commit

Permalink
add computedResult
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuaboud committed May 31, 2024
1 parent 1465326 commit 837ea11
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
33 changes: 33 additions & 0 deletions houston-common-ui/lib/composables/computedResult.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { ResultAsync, Result } from "neverthrow";
import { watchEffect, ref, type Ref } from "vue";

/**
* Create a computed ref that grabs it's value from a {@link Result} or {@link ResultAsync},
* returning computed ref and a manual update trigger function.
* @param getter function that returns a result of T
* @returns [reference: ComputedRef\<T | undefined\>, triggerUpdate: () => void]
*/
export function computedResult<T>(
getter: () => Result<T, any> | ResultAsync<T, any>
): [reference: Readonly<Ref<T | undefined>>, triggerUpdate: () => void];
/**
* Create a computed ref with default value that grabs it's value from a {@link Result} or {@link ResultAsync},
* returning computed ref and a manual update trigger function.
* @param getter function that returns a result of T
* @param defaultValue the default value before the Result is determined
* @returns [reference: ComputedRef\<T\>, triggerUpdate: () => void]
*/
export function computedResult<T>(
getter: () => Result<T, any> | ResultAsync<T, any>,
defaultValue: T
): [reference: Readonly<Ref<T>>, triggerUpdate: () => void];
export function computedResult<T>(
getter: () => Result<T, any> | ResultAsync<T, any>,
defaultValue?: T
): [reference: Readonly<Ref<T | undefined>>, triggerUpdate: () => void] {
const reference = ref<T>();
reference.value = defaultValue;
const triggerUpdate = () => getter().map((v) => (reference.value = v));
watchEffect(triggerUpdate);
return [reference, triggerUpdate];
}
1 change: 1 addition & 0 deletions houston-common-ui/lib/composables/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ export {
confirmBeforeAction,
assertConfirm,
} from "./globalModalConfirm";
export * from "./computedResult";

0 comments on commit 837ea11

Please sign in to comment.