Does it make sense using Vue 3 reactivity on a service? - vue-component

I have found following DataTable code snippet by PrimeVue, that uses the new Compositon API
<script>
import { ref, onMounted } from 'vue';
import ProductService from './service/ProductService';
export default {
setup() {
onMounted(() => {
productService.value.getProductsSmall().then(data => products.value = data);
})
const products = ref();
const productService = ref(new ProductService());
^^^^^^^^^^^^^^^^^^^^^^^^^^
return { products, productService }
}
}
</script>
Does it make any sense to ref() the ProductService?
I guess it does not. Am I wrong?

I believe you are correct, the assignment to ref is unnecessary.
I thought that might have been added for consistence with the options API:
import ProductService from './service/ProductService';
export default {
data() {
return {
products: null
}
},
productService: null,
created() {
this.productService = new ProductService();
},
mounted() {
this.productService.getProductsSmall().then(data => this.products = data);
}
}
However the productService is not part of the data object, so it is not reactive, and because it is a service that doesn't hold state it doesn't need to be.

Related

Testing event emitted from child component with Vitest & Vue-Test-Utils

I want to test if "onLogin" event emitted from child component will trigger "toLogin" function from parent correctly.
Login.vue
<template>
<ChildComponent
ref="child"
#onLogin="toLogin"
/>
</template>
<script>
import { useAuthStore } from "#/stores/AuthStore.js"; //import Pinia Store
import { userLogin } from "#/service/authService.js"; // import axios functions from another js file
import ChildComponent from "#/components/ChildComponent.vue";
export default {
name: "Login",
components: {
ChildComponent,
},
setup() {
const AuthStore = useAuthStore();
const toLogin = async (param) => {
try {
const res = await userLogin (param);
AuthStore.setTokens(res);
} catch (error) {
console.log(error);
}
};
}
</script>
login.spec.js
import { describe, it, expect, vi, beforeAll } from 'vitest';
import { shallowMount, flushPromises } from '#vue/test-utils';
import { createTestingPinia } from "#pinia/testing";
import Login from "#/views/user/Login.vue"
import { useAuthStore } from "#/stores/AuthStore.js";
describe('Login', () => {
let wrapper = null;
beforeAll(() => {
wrapper = shallowMount(Login, {
global: {
plugins: [createTestingPinia({ createSpy: vi.fn })],
},
});
})
it('login by emitted events', async () => {
const AuthStore = useAuthStore();
const loginParam = {
email: 'dummy#email.com',
password: '12345',
};
const spyOnLogin = vi.spyOn(wrapper.vm, 'toLogin');
const spyOnStore = vi.spyOn(AuthStore, 'setTokens');
await wrapper.vm.$refs.child.$emit('onLogin', loginParam);
await wrapper.vm.$nextTick();
await flushPromises();
expect(spyOnLogin).toHaveBeenCalledOnce(); // will not be called
expect(spyOnStore).toHaveBeenCalledOnce(); // will be called once
})
}
I expected both "spyOnLogin" and "spyOnStore" will be called once from emitted event, however, only "spyOnStore" will be called even though "spyOnStore" should only be called after "spyOnLogin" has been triggered.
The error message is:
AssertionError: expected "toLogin" to be called once
❯ src/components/__tests__:136:24
- Expected "1"
+ Received "0"
What do I fail to understand about Vitest & Vue-Test-Utils?
You shouldn't mock your toLogin method because its part of Login component which you are testing. Therefore, instead of expecting if toLogin has been called, you should check if instructions inside are working correctly.
In your case i would only test if after emit, userLogin and AuthStore.setTokens has been called.

Vue3 Composition API emit works without store but not with store

I am using Vue3 with the composition API. I have set up a store (not using VUEX) to store global settings. I have a sidebar that I want to expand or collapse. I first put all of the code in one component to emit to the parent to expand or collapse a sidebar, works great. I then tried to refactor to use the store to have the sidebar set across a views but the emit will not work in the second version.
Without using the store, all code is local to the component. It works great and emits the value to the parent.
//regular
import { ref } from "vue";
export default {
name: "rightmenu",
emits: ["showRightMenu"],
props: ["bgcolor"],
setup(props, context) {
const showRightMenu = ref(true);
function toggleRightMenu() {
if (showRightMenu.value == false) {
showRightMenu.value = true;
} else {
showRightMenu.value = false;
}
context.emit("showRightMenu", showRightMenu.value);
}
return { showRightMenu, toggleRightMenu };
},
};
The following uses the store to update the item and run methods.
//with store
import { ref, inject } from "vue";
export default {
name: "rightmenu",
emits: ["showRightMenu"],
props: ["bgcolor"],
setup(context) {
const store = inject("store");
const showRightMenu = ref(store.showRightMenu);
function toggleRightMenu() {
const aValue = store.methods.toggleRightMenu();
context.emit("showRightMenu", aValue); //ISSUE
}
return { showRightMenu, toggleRightMenu };
},
};
I get the following error:
Uncaught TypeError: context.emit is not a function
at Proxy.toggleRightMenu
Here is the store code:
import { ref } from "vue";
const showRightMenu = ref(true);
const methods = {
changeColor(val) {
state_color.color = val.color;
state_color.colorName = val.title;
},
toggleRightMenu() {
if (showRightMenu.value == false) {
showRightMenu.value = true;
} else {
showRightMenu.value = false;
}
return showRightMenu.value
},
};
const getters = {};
export default {
showRightMenu,
methods,
getters,
};
It looks like your setup function is incorrect.
in the first example, you are using the props as first argument, but not in the second.
setup(props, context) { works
setup(context) { doesn't because the context arg is actually populated by props and not context

Composition API - Axios request in setup()

I am experimenting with Vue3's Composition API in a Laravel/VueJS/InertiaJS stack.
A practice that I have used a lot in Vue2 with this stack is to have 1 route that returns the Vue page component (eg. Invoices.vue) and then in the created() callback, I would trigger an axios call to an additional endpoint to fetch the actual data.
I am now trying to replicate a similar approach in Vue3 with composition API like so
export default {
components: {Loader, PageBase},
props: {
fetch_url: {
required: true,
type: String,
}
},
setup(props) {
const loading = ref(false)
const state = reactive({
invoices: getInvoices(),
selectedInvoices: [],
});
async function getInvoices() {
loading.value = true;
return await axios.get(props.fetch_url).then(response => {
return response.data.data;
}).finally(() => {
loading.value = false;
})
}
function handleSelectionChange(selection) {
state.selectedInvoices = selection;
}
return {
loading,
state,
handleSelectionChange,
}
}
}
This however keeps on giving me the propise, rather than the actual data that is returned.
Changing it like so does work:
export default {
components: {Loader, PageBase},
props: {
fetch_url: {
required: true,
type: String,
}
},
setup(props) {
const loading = ref(false)
const state = reactive({
invoices: [],
selectedInvoices: [],
});
axios.get(props.fetch_url).then(response => {
state.invoices = response.data.data;
}).finally(() => {
loading.value = false;
})
function handleSelectionChange(selection) {
state.selectedInvoices = selection;
}
return {
loading,
state,
handleSelectionChange,
}
}
}
I want to use function though, so I can re-use it for filtering etc.
Very curious to read how others are doing this.
I have been googling about it a bit, but cant seem to find relevant docu.
All feedback is highly welcomed.
I tried this now with async setup() and await getInvoices() and <Suspense> but it never displayed any content.
So this is how I'd do it, except I wouldn't and I'd use vuex and vuex-orm to store the invoices and fetch the state from the store.
<template>
<div>loading:{{ loading }}</div>
<div>state:{{ state }}</div>
</template>
<script>
import {defineComponent, ref, reactive} from "vue";
import axios from "axios";
export default defineComponent({
name: 'HelloWorld',
props: {
fetch_url: {
required: true,
type: String,
}
},
setup(props) {
const loading = ref(false)
const state = reactive({
invoices: []
})
async function getInvoices() {
loading.value = true;
await axios.get(props.fetch_url).then(response => {
state.invoices = response.data;
}).finally(() => {
loading.value = false;
})
}
return {
getInvoices,
loading,
state,
}
},
async created() {
await this.getInvoices()
}
})
</script>
<style scoped>
</style>
This is of course similar to what you're doing in option 2.

Vue 3 compoition API computed function

Trying to switch my code to the new composition API that comes with Vue 3 but I cant get it to work.
export default {
props: {
classProp: {type: String},
error: {type: String},
},
setup(){
// move to here (this is not working)
computed(() => {
const classObject = () => {
return ['form__control', this.classProp,
{
'form__invalid': this.error
}
]
}
})
},
computed: {
classObject: function () {
return ['form__control', this.classProp,
{
'form__invalid': this.error
}
]
}
},
}
skip "computed" all together
you need to use "ref" or "reactive". these are modules:
<script>
import { ref } from 'vue'
setup(){
const whateverObject = ref({ prop: "whatever initial value" });
whateverObject.value.prop= "if you change something within setup you need to access it trough .value";
return { whateverObject } // expose it to the template by returning it
}
</script>
if you want to use classes you import them like in this example of my own:
import { APIBroker } from '~/helpers/APIbroker'
const api = new APIBroker({})
Now "api" can be used inside setup() or wherever

Throtting same saga/epic action with takeLatest on different actions

I'm new on redux-saga/observable stuff. But I couldn't handle my scenario which looks so fit on these. So; I want to call API if any changes happen on the form. But I don't want to call API a lot because of the performance reasons.
Basically, when I trigger SLIDERCHANGED, TEXTBOXCHANGED, CHECKBOXCHECKED, I want to call also getData function. But I need to put a delay to check other actions. For example; If SLIDERCHANGED is triggered, It should wait for 1sn and if TEXTBOXCHANGED is triggered at that time, It will be canceled and wait for 1sn more to call the getData function. So that's why I tried to implement Redux-saga or redux-observable.
I have actions types;
const SLIDERCHANGED = 'APP/sliderchanged';
const TEXTBOXCHANGED = 'APP/textboxchanged';
const CHECKBOXCHECKED = 'APP/checkboxchecked';
const LOADING = 'APP/loading';
const LOADDATA = 'APP/loaddata';
const ERRORLOADDATA = 'APP/errorloaddata';
I have also actions;
export function updateSliderValue(val) {
return { type: SLIDERCHANGED, val };
}
export function updateTextboxValue(val) {
return { type: TEXTBOXCHANGED, val };
}
export function updateCheckboxValue(val) {
return { type: CHECKBOXCHECKED, val };
}
export function loading() {
return { type: LOADING };
}
export function loadData(data) {
return { type: LOADDATA, data };
}
export function errorLoadData(err) {
return { type: ERRORLOADDATA, err };
}
export function getData(vehicleInfo) { // redux-thunk ASYNC function
return (dispatch, getState) => {
dispatch(loading());
return dispatch(apiCall('/getAllData', {}))
.then(payload => {
dispatch(loaddata(payload));
})
.catch(error => {
dispatch(errorLoadData(error));
});
};
}
With redux-saga, I did this but it doesn't work. It calls a getData function on each change with 1sn delay.
import { put, throttle } from 'redux-saga/effects';
import {
SLIDERCHANGED,
TEXTBOXCHANGED,
CHECKBOXCHECKED
} from './constants';
import { getData } from './actions';
function* onFormUpdate() {
yield put(getData());
}
export function* watchFormChange() {
yield throttle(
10000,
[SLIDERCHANGED, TEXTBOXCHANGED, CHECKBOXCHECKED],
onFormUpdate
);
}
With redux-observable, Also somehow I get the same error.
import { ofType } from 'redux-observable';
import { delay, map, debounceTime } from 'rxjs/operators';
import {
SLIDERCHANGED,
TEXTBOXCHANGED,
CHECKBOXCHECKED
} from './constants';
import { getData } from './actions';
export const onFormUpdate = action => {
return action.pipe(
ofType(SLIDERCHANGED, TEXTBOXCHANGED, CHECKBOXCHECKED),
debounceTime(1000),
map(() => getData())
);
};
Does anyone have any idea or opinion to make this happen?
Without having tested it, I think you can write a solution like this:
import { delay } from 'redux-saga'
import { put } from 'redux-saga/effects'
function* onFormUpdate() {
yield delay(1000)
yield put(getData())
}
export function* watchFormChange() {
yield takeLatest(
[SLIDERCHANGED, TEXTBOXCHANGED, CHECKBOXCHECKED],
onFormUpdate,
)
}
The idea here is that takeLatest will cancel onFormUpdate as soon as another one of the three actions is dispatched. So while onFormUpdate is in delay and then canceled, the next step, which is put, will not be called anymore.

Resources