Responsive asynchronous request status
Arno Solo
Posted on September 28, 2022
Can anyone tell me did I did it right?
- pages/products.vue
<template>
<div v-if="fetchDataState.isFetching" py-4 w-full flex justify-center>
<spinner />
</div>
<div v-else-if="fetchDataState.isFailed" text-center py-4>
Load failed
</div>
<product-list v-else :products="products" />
</template>
<script setup lang="ts">
const { products, fetchDataState } = useProductsByCatalog();
</script>
- composables/useProductsByCatalog.ts
export function useProductsByCatalog(catalogId: string) {
const { products, setProducts } = useProducts();
const { fetchDataState } = useFetchDataState();
onMounted(() => {
fetchDataState.isFetching = true;
setTimeout(() => {
fetchDataState.isSuccess = true;
setProducts(xxx)
}, 1000);
});
return {
products,
fetchDataState,
};
};
- composables/useFetchDataState.ts
enum AsyncReqState {
beforeReq,
waitRes,
success,
failed,
}
class FetchDataState {
reqState: AsyncReqState;
constructor() {
this.reqState = AsyncReqState.beforeReq;
this.isFetching = false;
}
set isBeforeReq(newVal: boolean) {
if (newVal) {
this.reqState = AsyncReqState.beforeReq;
}
}
get isBeforeReq() {
return this.reqState === AsyncReqState.beforeReq;
}
set isFetching(newVal: boolean) {
if (newVal) {
this.reqState = AsyncReqState.waitRes;
}
}
get isFetching() {
return this.reqState === AsyncReqState.waitRes;
}
set isSuccess(newVal: boolean) {
if (newVal) {
this.reqState = AsyncReqState.success;
}
}
get isSuccess() {
return this.reqState === AsyncReqState.success;
}
set isFailed(newVal: boolean) {
if (newVal) {
this.reqState = AsyncReqState.failed;
}
}
get isFailed() {
return this.reqState === AsyncReqState.failed;
}
}
export function useFetchDataState() {
const fetchDataState = reactive<FetchDataState>(new FetchDataState());
return {
fetchDataState,
};
}
💖 💪 🙅 🚩
Arno Solo
Posted on September 28, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev Learn How to Create an Interactive Map of India Using HTML5/JavaScript and SVG
January 8, 2024
webdev Creating HTML Templates for Binding JSON Data with JavaScript Template Literals
January 12, 2024