Skip to content

Instantly share code, notes, and snippets.

@coltborg
Created December 11, 2019 01:26
Show Gist options
  • Save coltborg/86af5b8ec480f9c2e868b4fe6e163c8b to your computer and use it in GitHub Desktop.
Save coltborg/86af5b8ec480f9c2e868b4fe6e163c8b to your computer and use it in GitHub Desktop.
Vue 3 Essentials - Sharing state
import { ref } from "@vue/composition-api"
export default function usePromise(fn) {
const results = ref(null);
const loading = ref(false);
const error = ref(null);
const createPromise = async (..args) => {
loading.value = true;
error.value = null;
results.value = null;
try {
results.value = await fn(...args);
} catch (err) {
error.value = err;
} finally {
loading.value = false;
}
}
return { createPromise, error, loading, results };
}
<template>
<div>
Search for <input v-model="searchInput" />
<div>
<p>Loading: {{ getEvents.loading }}</p>
<p>Error: {{ getEvents.error }}</p>
<p>Number of events: {{ getEvents.results }}</p>
</div>
</div>
</template>
<script>
import { ref, watch } from "@vue/composition-api";
import eventApi from "@/api/event.js";
import usePromise from "@/composables/use-promise";
export default {
setup() {
const searchInput = ref("");
const getEvents = usePromise(search => eventApi.getEventCount(search.value););
watch(searchInput, () => {
if (searchInput.value !== "") {
getEvents.createPromise(searchInput);
} else {
results.value = null;
}
});
return { getEvents, searchInput };
}
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment