2.1.0 • Published 2 years ago

@joaomelo/composables v2.1.0

Weekly downloads
-
License
GPL-3.0
Repository
github
Last release
2 years ago

vue composables

use-Command

composable to help vue components deal with async functions that conform the command arbitrary shape

what is a command

an async function that does not return anything and accepts two parameters:

  • payload object that can change each execution
  • dependencies object that can hold reference external services like apis or db drivers`
async function addTodo(payload, { db }) {
  const { title } = payload;
  const item = {
    id: createUuid(),
    title,
    completed: false,
  };
  await db.set(item);
}

payloads and dependencies are always objects and can not expect primitive values like string or booleans.

how to use de composable

useCommand accepts two arguments

  • the command function to wrapper
  • a config object with a optional reference to the payload, dependencies do pass and a error schema description

and returns an array with

  • a execute function
  • boolean ref to signal execution
  • object ref with the error report conforming to the schema
import { reactive } from "vue";
import { useCommand } from "@joaomelo/composables";
import { addTodo } from "./add.js";

const dependencies = { ... };
const schema = { ... };
const payload = reactive({ title: "" });

const [add, isLoading, errorReport] = useCommand(addTodo, {
  payload,
  dependencies,
  schema
});

...

<SomeForm :error="error.escaped" :is-loading="isLoading">
    <SomeField v-model="payload.title" :error="error.title"/>
    <SomeButton @click="add">add</SomeButton>
</SomeForm>

if you don't pass a payload reference on the useCommand call, you can still do it when calling the execute function.

useSubscribe

you can pass one or more observables and get a vue ref that keeps the observable current value in sync.

the observable should be a compatible rxjs observable.

the composable will unsubscribe when the component unmounts.

you can also pass an optional initial value and project function to process the latest value for each observable.