[Vuejs]-How to destructure a composable?

0👍

I found two solutions.

First Solution

As mentioned by @EstusFlask in the comments, I could just remove the return type.

In that case the composable beomes:

import { ref } from "vue";

const getDocument = <T>(docId: string) => {
  const document = ref<T | null>(null);
  const error = ref<string | null>(null);

  const docFromDatabase = getdocFromDatabase(docId);

  document.value = {
    ...docFromDatabase.data(),
    id: docFromDatabase.id,
  };

  error.value = "Some error text here";

  return { document, error };
};

export default getDocument;

Second Solution

The other way I found is to keep the return type, but use const document = ref(null) as Ref<T | null>; to cast document as Ref<T | null>.

This also removes the error on document and has the added bonus of satisfying ESLint which complains when there is no return type on complex functions.

import { ref, Ref } from "vue";

const getDocument = <T>(
  docId: string
): {
  document: Ref<T | null>;
  error: Ref<string | null>;
} => {
  const document = ref(null) as Ref<T | null>;
  const error = ref<string | null>(null);

  const docFromDatabase = getdocFromDatabase(docId);

  document.value = {
    ...docFromDatabase.data(),
    id: docFromDatabase.id,
  };

  error.value = "Some error text here";

  return { document, error };
};

export default getDocument;

Leave a comment