Can I use watch from Vue 3 with primitives? - vue.js

Every time I fetch data, I want to change boolean value to render <Loading /> component.
I don't want my condition to be dependant on array length. So I decided to do it this way.
And <Loading /> component never reacts to state.isLoading change.
I tried to test whether this.isLoading changes at all using watch. But watch never logged anything.
I've never seen anybody using watch with primitives.
The problem is that I don't know if I can use watch with primitives and what I can use instead, like useEffect in React.
App.vue
<script setup>
import { RouterView } from 'vue-router'
import { watch, ref, onMounted, reactive } from 'vue';
import Navbar from './components/Navbar.vue'
import { useShopStore } from './stores/shopStore';
const shop = useShopStore()
const bool = ref(shop.isLoading)
console.log(bool)
watch(bool.value, (newBool) => {
console.log(newBool)
}, { deep: true })
</script>
Category.vue
<template>
<LoadingVue v-if="shop.isLoading" />
<div v-else class="category__menu">
<CardVue
v-for="item in shop.category"
:item="item"
:key="item.id"
/>
</div>
</template>
ShopStore.js
actions: {
async getProducts(path) {
if (typeof path !== 'string' || path === undefined) return
this.setLoading()
try {
const response = fetch(`https://fakestoreapi.com/products/category/${path}`)
.then(res => res.json())
.then(res => this.category = res)
} catch (error) {
console.log(error)
alert('Something went wrong')
}
this.setLoading()
},
setLoading() {
console.log('setLoading')
this.isLoading = !this.isLoading
}
}

You are creating a new ref over a reactive data. It's like copying by value, the original reactive data and the new ref wrapped over it are not connected. So when shop.isLoading changes, your bool ref doesn't, they are two different variables now.
I guess you are using pinia for the store. If so, the shop.isLoading is already reactive, you don't have to wrap it into a ref.
<Loading v-model="shop.isLoading" />
You can also use storeToRefs helper method from pinia to use destructuring over your store and get refs of your state:
const { isLoading } = storeToRefs(shop)
console.log(isLoading.value)

So.
The problem was that I used async but I didn't use await inside the function and that's why condition worked the way it worked. Or didn't work as I expected.
Now I fixed it and I want to publicly admit that I am a complete moron.
Thank you for your attention.
P.S.
Still didn't figure out how to use watch. The only way is to watch the whole state object. watch doesn't react to only state.bool value change.

Related

Composition API | Vue route params not being watched

I have pretty much the same example from the docs of watch and vue router for composition API. But console.log is never getting triggered even though the route.params.gameId is correctly displayed in template
<script setup>
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useStore } from 'vuex'
const store = useStore()
const route = useRoute()
watch(
() => route.params.gameId,
async newId => {
console.log("watch"+newId)
}
)
</script>
<template>
<div>
{{route.params.gameId}}
</div>
</template>
What am I doing wrong? I also tried making watch function non async but it didn't change anything and later on I will need it for api fetching so it should be async.
You should add immediate: true option to your watch :
watch(
() => route.params.gameId,
async newId => {
console.log("watch"+newId)
},
{
immediate: true
}
)
Because the watch doesn't run at the first rendering while the params is changes only one time at the page load, So the watch misses that change.

Vuex is resetting already set states

Have started to play around with Vuex and am a bit confused.
It triggers the action GET_RECRUITERS everytime I load the component company.vue thus also making an api-call.
For example if I open company.vue => navigate to the user/edit.vue with vue-router and them go back it will call the action/api again (The recruiters are saved in the store accordinly to Vue-dev-tools).
Please correct me if I'm wrong - It should not trigger the action/api and thus resetting the state if I go back to the page again, correct? Or have I missunderstood the intent of Vuex?
company.vue
<template>
<card>
<select>
<option v-for="recruiter in recruiters"
:value="recruiter.id">
{{ recruiter.name }}
</option>
</select>
</card>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
middleware: 'auth',
mounted() {
this.$store.dispatch("company/GET_RECRUITERS")
},
computed: mapGetters({
recruiters: 'company/recruiters'
}),
}
</script>
company.js
import axios from 'axios'
// state
export const state = {
recruiters: [],
}
// getters
export const getters = {
recruiters: state => {
return state.recruiters
}
}
// actions
export const actions = {
GET_RECRUITERS(context) {
axios.get("api/recruiters")
.then((response) => {
console.log('API Action GET_RECRUITERS')
context.commit("GET_RECRUITERS", response.data.data)
})
.catch(() => { console.log("Error........") })
}
}
// mutations
export const mutations = {
GET_RECRUITERS(state, data) {
return state.recruiters = data
}
}
Thanks!
That's expected behavior, because a page component is created/mounted again each time you route back to it unless you cache it. Here are a few design patterns for this:
Load the data in App.vue which only runs once.
Or, check that the data isn't already loaded before making the API call:
// Testing that your `recruiters` getter has no length before loading data
mounted() {
if(!this.recruiters.length) {
this.$store.dispatch("company/GET_RECRUITERS");
}
}
Or, cache the page component so it's not recreated each time you route away and back. Do this by using the <keep-alive> component to wrap the <router-view>:
<keep-alive>
<router-view :key="$route.fullPath"></router-view>
</keep-alive>

Vue 3 Composition API reuse in multiple components

I have these files
App.vue, Header.vue, search.js and Search.vue
App.vue is normal and just adding different views
Header.vue has an input box
<input type="text" v-model="searchPin" #keyup="searchResults" />
<div>{{searchPin}}</div>
and script:
import useSearch from "#/compositions/search";
export default {
name: "Header",
setup() {
const { searchPin, searchResults } = useSearch();
return {
searchPin,
searchResults
};
}
};
search.js has the reusable code
import { ref } from "vue";
export default function useSearch() {
const searchPin = ref("");
function searchResults() {
return searchPin.value;
}
return {
searchPin,
searchResults
};
}
Now, this is working well.. once you add something on the input box, it is showing in the div below.
The thing I have not understood is how to use this code to a third component like Search.vue.
I have this, but its not working.
<template>
<div>
<h1 class="mt-3">Search</h1>
<div>{{ searchPin }}</div>
</div>
</template>
<script>
import useSearch from "#/compositions/search";
export default {
name: "Search",
setup() {
const { searchPin, searchResults } = useSearch();
return {
searchPin,
searchResults
};
}
};
</script>
What am I missing? Thanks.
The fix for this is very simple
instead of
import { ref } from "vue";
export default function useSearch() {
const searchPin = ref("");
function searchResults() {
return searchPin.value;
}
return {
searchPin,
searchResults
};
}
use
import { ref } from "vue";
const searchPin = ref("");
export default function useSearch() {
function searchResults() {
return searchPin.value;
}
return {
searchPin,
searchResults
};
}
The problem is that the searchPin is scoped to the function, so every time you call the function, it gets a new ref. This is a desirable effect in some cases, but in your case, you'll need to take it out.
Here is an example that uses both, hope it clears it up.
const {
defineComponent,
createApp,
ref
} = Vue
const searchPin = ref("");
function useSearch() {
const searchPinLoc = ref("");
function searchResults() {
return searchPin.value + "|" + searchPinLoc.value;
}
return {
searchPin,
searchPinLoc,
searchResults
};
}
const HeaderComponent = defineComponent({
template: document.getElementById("Header").innerHTML,
setup() {
return useSearch();
},
})
const SearchComponent = defineComponent({
template: document.getElementById("Search").innerHTML,
setup() {
return useSearch();
}
})
createApp({
el: '#app',
components: {
HeaderComponent, SearchComponent
},
setup() {}
}).mount('#app')
<script src="https://unpkg.com/vue#3.0.0-rc.9/dist/vue.global.js"></script>
<div id="app">
<header-component></header-component>
<search-component></search-component>
</div>
<template id="Header">
searchPin : <input type="text" v-model="searchPin" #keyup="searchResults" />
searchPinLoc : <input type="text" v-model="searchPinLoc" #keyup="searchResults" />
<div>both: {{searchResults()}}</div>
</template>
<template id="Search">
<div>
<h1 class="mt-3">Search</h1>
<div>both: {{searchResults()}}</div>
</div>
</template>
Adding flavor to #Daniel 's answer.
This is exactly what I'm struggling with regarding to best practices ATM and came to some conclusions:
Pulling the Ref outside of the composition fn would fix your problem but if you think about it, it's like sharing a single instance of a data property used in multiple places. You should be very careful with this, since ref is mutable for whoever pulls it, and will easily break unidirectional data flow.
For e.g. sharing a single Ref instance between a parent component and a child components can be compared to passing it down from parent's data to child's props, and as I assume we all know we should avoid mutating props directly
So classical answer for your question would be, move it to Vuex state and read it from there.
But if you have a small application, don't want a state manager, or simply want to take full advantage of the composition API, then my suggestion would be to at least do something of this pattern
import { ref, computed } from "vue";
const _searchPin = ref(""); // Mutable persistant prop
const searchPin = computed(() => _searchPin.value); // Readonly computed prop to expose
export default function useSearch() {
function searchResults() {
return searchPin.value;
}
return {
searchPin,
searchResults
};
}
Not more than ONE component should mutate the persistent Ref while others could only listen to the computed one.
If you find that more than one component needs access to change the ref, then that's probably a sign you should find another way to implement this (Vuex, props and events, etc...)
As I said, I am still trying to make sense of this myself and am not sure this is a good enough pattern either, but it's definitely better then simply exposing the instance.
Another option for code arrangement would be to encapsulate in 2 different access hooks
import { ref, readonly } from "vue";
const searchPin = ref(""); // Mutable persistant prop
export const useSearchSharedLogic() {
return readonly({
searchPin
})
}
const useSearchWriteLogic() {
return {
searchPin
}
}
// ----------- In another file -----------
export default function useSearch() {
const { searchPin } = useSearchSharedLogic()
function searchResults() {
return searchPin.value;
}
return {
searchPin,
searchResults
};
}
Or something of this sort (Not even sure this would work correctly as written).
Point is, don't expose a single instance directly
Another point worth mentioning is that this answer takes measure to preserve unidirectional data flow pattern. Although this is a basic proven pattern for years, it's not carved in stone. As composition patterns get clearer in the close time, IMO we might see people trying to challenge this concept and returning in some sense to bidirectional pattern like in Angular 1, which at the time caused many problems and wasn't implemented well

Lazy loading a specific component in Vue.js

I just make it quick:
In normal loading of a component (for example "Picker" component from emoji-mart-vue package) this syntax should be used:
import {Picker} from "./emoji-mart-vue";
Vue.component("picker", Picker);
And it works just fine.
But when I try to lazy load this component I'm not sure exactly what code to write. Note that the following syntax which is written in the documentation doesn't work in this case as expected:
let Picker = ()=>import("./emoji-mart-vue");
The problem, I'm assuming, is that you're using
let Picker = ()=>import("./emoji-mart-vue");
Vue.component("picker", Picker);
to be clear, you're defining the component directly before the promise is resolved, so the component is assigned a promise, rather than a resolved component.
The solution is not clear and depends on "what are you trying to accomplish"
One possible solution:
import("./emoji-mart-vue")
.then(Picker=> {
Vue.component("picker", Picker);
// other vue stuff
});
This will (block) wait until the component is loaded before loading rest of the application. IMHO, this defeats the purpose of code-spliting, since the application overall load time is likely worse.
Another option
is to load it on the component that needs it.
so you could put this into the .vue sfc that uses it:
export default {
components: {
Picker: () => import("./emoji-mart-vue")
}
};
But this would make it so that all components that use it need to have this added, however, this may have benefits in code-splitting, since it will load only when needed the 1st time, so if user lands on a route that doesn't require it, the load time will be faster.
A witty way to solve it
can be done by using a placeholder component while the other one loads
const Picker= () => ({
component: import("./emoji-mart-vue"),
loading: SomeLoadingComponent
});
Vue.component("picker", Picker);
or if you don't want to load another component (SomeLoadingComponent), you can pass a template like this
const Picker= () => ({
component: import("./emoji-mart-vue"),
loading: {template:`<h1>LOADING</h1>`},
});
Vue.component("picker", Picker);
In PluginPicker.vue you do this:
<template>
<picker />
</template>
<script>
import { Picker } from "./emoji-mart-vue";
export default {
components: { Picker }
}
</script>
And in comp where you like to lazy load do this:
The component will not be loaded until it is required in the DOM, which is as soon as the v-if value changes to true.
<template>
<div>
<plugin-picker v-if="compLoaded" />
</div>
</template>
<script>
const PluginPicker = () => import('./PluginPicker.vue')
export default {
data() = { return { compLoaded: false }}
components: { PluginPicker }
}
// Another syntax
export default {
components: {
PluginPicker: () => import('./PluginPicker.vue')
}
}
</script>

Is `async/await` available in Vue.js `mounted`?

I'd like to do something like this in mounted() {}:
await fetchData1();
await fetchData2UsingData1();
doSomethingUsingData1And2();
So I wonder if this works:
async mounted() {
await fetchData1();
await fetchData2UsingData1();
doSomethingUsingData1And2();
},
In my environment it raises no errors, and seems to work well.
But in this issue, async/await in lifecycle hooks is not implemented.
https://github.com/vuejs/vue/issues/7209
I could not find further information, but is it available in fact?
It will work because the mounted hook gets called after the component was already mounted, in other words it won't wait for the promises to solve before rendering. The only thing is that you will have an "empty" component until the promises solve.
If what you need is the component to not be rendered until data is ready, you'll need a flag in your data that works along with a v-if to render the component when everything is ready:
// in your template
<div v-if="dataReady">
// your html code
</div>
// inside your script
data () {
return {
dataReady: false,
// other data
}
},
async mounted() {
await fetchData1();
await fetchData2UsingData1();
doSomethingUsingData1And2();
this.dataReady = true;
},
Edit: As stated in the documentation, this is an experimental feature and should not be used in production applications for now.
The correct way to do this in vue3 would be to make your setup() function async like this:
<script>
// MyComponent.vue
export default defineComponent({
/* ... */
async setup() {
await fetchData1();
await fetchData2UsingData1();
doSomethingUsingData1And2();
this.dataReady = true;
}
}
</script>
And then use a suspense component in the parent to add a fallback like this:
<template>
<Suspense>
<template #default>
<MyComponent />
</template>
<template #fallback>
Loading...
</template>
</Suspense>
</template>
So you would see the #fallback template while the component is loading, and then the component itself when it's ready.
Just use $nextTick to call async functions.