I have the following VueRouter route
{
path: '/playlists/:id',
name: 'videos',
component: Video,
props: {
videos: [],
},
beforeEnter(to, from, next) {
Vue.axios
.get('/playlistitems?playlistId='.concat(to.params.id))
.then((response) => {
to.params.videos = response.data
next((vm) => {
console.log(vm)
vm.videos = response.data
})
})
.catch((err) => console.log('error', err))
},
}
When the route is entered into everything executes as expected but I'm not sure how to pass the response.data to the route's component Videos
Question 1
Can you set the Vue component's props property from the Router?
Question 2
The route is a dynamic route. If the route and component is already loaded and the dynamic parameter changes....does beforeEnter still fire? If not where should I put my data fetching logic? Do I watch for route changes inside the Vue component?
1)
This might not be the most elegant approach, but here's a way to achieve that:
let videos = [];
export default new Router({ ... });
{
path: '/playlists/:id',
name: 'videos',
component: Video,
props: route => ({ videos }),
beforeEnter (to, from, next) {
Vue.axios.get('/playlistitems?playlistId='.concat(to.params.id))
.then((response) => {
// Now the data will be available when the props will be initialized
videos = response.data
next()
})
.catch((err) => console.log('error', err))
}
}
// Videos.vue
props: {
videos: Array
},
2)
IMHO, it would be easier if you could encapsulate the logic in the component.
What do I mean by that is that you could fetch your data in the created hook and set it to a variable that you defined in your data function.
data() {
return {
videos: []
}
},
created () {
Vue.axios.get('/playlistitems?playlistId='.concat(this.$route.params.id))
.then((response) => {
this.videos = response.data;
})
.catch((err) => console.log('error', err))
},
Another approach, which may be suitable or not, depending on what you're working on, would be to have a parent component that fetches multiple playlists which could be stored in vuex.
Thus, you would have another component that handles playlists/:id.
Within this last mentioned component, in your created hook, you would have something like this:
created () {
this.$store.commit('playlist/SET_CURRENT_PLAYLIST_ID', this.$route.params.id);
this.videos = this.$store.getters['playlits/getVideosByPlaylistId'];
},
Related
I have a couple of Pinia stores that should share a set of actions and getters and I’m not quite sure how to effectively achieve that.
I’m building an app that lets users manage a number of different media (Books, Movies, TV Shows, etc). The way I’m currently thinking about it is to have a store for each media type e.g. BookStore, MovieStore etc. A lot of the getters and actions (e.g., count and deleteOne) are exactly the same between those different stores.
How do I achieve DRY here? The Pinia documentation has examples that mostly focus around reusing actions and getters inside other stores but I don’t think that quite solves my use case of inheriting a set of getters and setters outright.
Is my attempted inheritance approach here an anti-pattern?
This is achievable using plugins docs
Example Movies:
You have multiple stores using shared naming scheme for each state:
item: single entity item (single movie details)
collection: collection of items (collection of all movies)
each store will have the same CRUD actions with only the URL changing
getCollection: get list of items from API and set response as collection (https://url.com/movies)
getItem: get single item from API and set response as item (https://url.com/movies/id)
handleError: displays alert to the user with error information
Create plugin:
function BaseStorePlugin () {
return {
collection: [],
item: {},
getCollection: function (url) {
api.get(url)
.then((response) => {
this.collection = response.data;
})
.catch((error) => {
this.handleError(error);
});
},
getItem: function (url) {
api.get(url)
.then((response) => {
this.item = response.data;
})
.catch((error) => {
this.handleError(error);
});
},
handleError: function (error) {
window.alert(error);
},
};
}
Give plugin to Pinia:
const pinia = createPinia();
pinia.use(BaseStorePlugin);
Example movieStore.js (using shared action & state)
import { defineStore } from 'pinia';
import { api } from 'src/boot/axios';
export const useMovieStore = defineStore({
id: 'movie',
state: () => ({
movieSpecificStateObject: {},
}),
actions: {
movieSpecificAction (url) {
console.log(this.item);
api.get(url)
.then((response) => {
// handle response
})
.catch((error) => {
this.handleError(error);
});
},
},
});
Example usage in component
<template>
<div
v-for="movie in movieStore.collection"
:key="movie.id"
>
<div>
{{ movie.name }}
</div>
</div>
</template>
<script setup>
import { onMounted } from 'vue';
import { useMovieStore } from 'src/stores/movieStore.js';
const movieStore = useMovieStore();
onMounted(() => {
movieStore.readCollection('http://url.com/movies');
});
</script>
Edit: 1
if you pass the context into the plugin you have access to the store and options being passed into it, from this you could check the store id and only return for specific stores like below
function BaseStorePlugin (context) {
const allowedStores = ['movie', 'album'];
if (allowedStores.includes(context.store.$id)) {
return {
collection: [],
getCollection: function () {
const fakeCollection = Array.from({length: 10}, () => Math.floor(Math.random() * 40));
fakeCollection.forEach((item) => {
this.collection.push({
id: item,
name: `name${item}`
});
});
},
};
};
}
I have created a very basic example using 3 stores and the above check available on codesandbox here
I have a works component I use different pages on my app and I am trying to load the state based on the route and route parameters.
In my App.vue file I dispatch the async action to get the json file like
mounted() {
this.$store.dispatch('getData')
},
And I map the state in my works component like that
export default {
name: 'Works',
computed: mapState({
works: (state) => state.works.home.items.slice(0, state.works.home.loadedCount),
loadedCount: (state) => state.works.home.loadedCount,
totalCount: (state) => state.works.home.items.length,
})
}
I actually need to map the state dynamically based on the route just like state.works[this.$router.currentRoute.params.category] or based on route name.
Could you please tell me what is the correct way to get the data (async) from my state?
Vuex store:
export default new Vuex.Store({
state: {
works: {
all: {
items: [],
loadedCount: 0,
},
home: {
items: [],
loadedCount: 0,
},
web: {
items: [],
loadedCount: 0,
},
print: {
items: [],
loadedCount: 0,
},
},
limit: 2,
},
mutations: {
SET_WORKS(state, works) {
state.works.all.items = works
works.map((el) => {
if (typeof state.works[el.category] !== 'undefined') {
state.works[el.category].items.push(el)
}
})
},
},
actions: {
getData({ commit }) {
axios
.get('/works.json')
.then((response) => {
commit('SET_WORKS', response.data.works)
})
},
},
})
You can do it in beforeCreate hook.
beforeCreate(){
const category = this.$route.params.category;
Object.assign(this.$options.computed, {
...mapState({
categoryItems: (state) => state.categories[category],
}),
});
}
I've created a basic working example: https://codepen.io/bgtor/pen/OJbOxKo?editors=1111
UPDATE:
To get mapped properties updated with route change, you will have to force re-render the component. The best way to do it, is to change the component key when route change in parent component.
Parent.vue
<template>
<categoryComponent :key="key"></categoryComponent> // <-- This is the component you work with
</template>
computed: {
key(){
return this.$route.params.category
}
}
With this approach the beforeCreate hook will be triggered with every route change, getting fresh data from Vuex.
I have a Vue component that calls a Vuex action in its create hook (an api.get that fetches some data, and then dispatches a mutation). After that mutation is completed, I need to call an action in a different store, depending on what has been set in my store's state... in this case, getUserSpecials.
I tried to use .then() on my action, but that mutation had not yet completed, even though the api.get Promise had resolved, so the store state I needed to check was not yet available.
Does anyone know if there is a 'best practice' for doing this? I also considered using a watcher on the store state.
In my component, I have:
created () {
this.getUserModules();
if (this.userModules.promos.find((p) => p.type === 'specials')) {
this.getUserSpecials();
}
},
methods: {
...mapActions('userProfile', ['getUserModules',],),
...mapActions('userPromos', ['getUserSpecials',],),
},
In my store I have:
const actions = {
getUserModules ({ commit, dispatch, }) {
api.get(/user/modules).then((response) => {
commit('setUserModules', response);
});
},
};
export const mutations = {
setUserModules (state, response) {
Object.assign(state, response);
},
};
Right now, the simple if check in my create hook works fine, but I'm wondering if there is a more elegant way to do this.
[1] Your action should return a promise
getUserModules ({ commit, dispatch, }) {
return api.get(/user/modules).then((response) => {
commit('setUserModules', response);
})
}
[2] Call another dispatch when the first one has been resolved
created () {
this.getUserModules().then(response => {
this.getUserSpecials()
})
}
Make your action return a promise:
Change:
getUserModules ({ commit, dispatch, }) {
api.get(/user/modules).then((response) => {
commit('setUserModules', response);
});
},
To:
getUserModules({commit, dispatch}) {
return new Promise((resolve, reject) => {
api.get(/user/modules).then((response) => {
commit('setUserModules', response);
resolve(response)
}).catch((error) {
reject(error)
});
});
},
And then your created() hook can be:
created () {
this.getUserModules().then((response) => {
if(response.data.promos.find((p) => p.type === 'specials'))
this.getUserSpecials();
}).catch((error){
//error
});
},
I am trying to fetch data from API using beforeEnter() route guard but I am getting an error:
Missing required prop: "rides"
Here's my code.
router.js
{
path: '/',
name: 'home',
component: () => import('./components/main.vue'),
props: true,
beforeEnter(to, from, next) {
store.dispatch('ride/fetchRides').then(rides => {
to.params.rides = rides
next()
})
}
}
actions.js
fetchRides({ commit, dispatch }) {
return statistcsService.ridesForCurrentWeek()
.then(response => {
commit('SET_RIDES', response.data)
return response.data
})
.catch(error => {
const notification = {
type: 'danger',
message: 'There was a problem fetching your rides'
}
dispatch('notification/add', notification, { root: true })
throw error
})
}
Index.vue
<script>
export default {
props: {
rides: {
type: Array,
required: true
}
}
...
}
</script>
What am I missing? The prop is set in the component so am I not sure why it is crying.
I have verified that in 100% I am getting the data from API response.
You forgot to add rides property in your html code for that component. According to the error message - that's the problem.
Example:
<component :rides="rides"></component>
For such component
<template>
<div>
<router-link :to="{name:'section', params: { sectionId: firstSectionId }}">Start</router-link>
</div>
</template>
<script lang="ts">
import { mapActions } from "vuex"
export default {
mounted() {
this.getSectionId()
},
computed: {
firstSectionId() {
return this.$store.state.firstSectionId
}
},
methods: mapActions(["getSectionId"])
}
</script>
Store:
const store: any = new Vuex.Store({
state: {
firstSectionId: null
},
// actions,
// mutations
})
I have a web request in the getSectionId action and it asynchronously fetches data and calls a mutation that will fill firstSectionId in state. During the initial rendering firstSectionId is null and I get the warning that a required parameter is missing during rendering of router-link.
It is not a problem here to add v-if="firstSectionId". But in general what is the approach for fetching data from a server to be displayed? Currently all my components are checking if there is data present in the store before rendering, is it normal or is there a better way to wait for data to be loaded before rendering it?
One approach for asynchronously fetching data is to use promise in vuex store actions.
Vue.http.get(API_URL)
.then((response) => {
//use response object
})
.catch((error) => {
console.log(error.statusText)
});
To demonstrate that I make request to this route. You can see how response should looks like. Let's save response object in state.users array.
store.js
const store = new Vuex.Store({
state: {
users: []
},
mutations: {
FETCH_USERS(state, users) {
state.users = users
}
},
actions: {
fetchUsers({ commit }, { self }) {
Vue.http.get("https://jsonplaceholder.typicode.com/users")
.then((response) => {
commit("FETCH_USERS", response.body);
self.filterUsers();
})
.catch((error) => {
console.log(error.statusText)
});
}
}
})
export default store
You noticed that there is self.filteruser() method after commit. That is crucial moment. Before that we are committing a mutation, which is synchronous operation and we are sure that we will have our response in store.state that can be used in filterUsers() method (don't forget to pass self parm)
Users.vue
import store from "../store/store"
export default {
name: 'users',
created() {
this.$store.dispatch("fetchUsers", { self: this })
},
methods:{
filterUsers() {
//do something with users
console.log("Users--->",this.$store.state.users)
}
}
}
Better ways (ES6 & ES7)
ES6 Promises for asynchronous programming
//User.vue
created() {
this.$store.dispatch("fetchUser").then(() => {
console.log("This would be printed after dispatch!!")
})
}
//store.js
actions: {
fetchUser({ commit }) {
return new Promise((resolve, reject) => {
Vue.http.get("https://jsonplaceholder.typicode.com/users")
.then((response) => {
commit("FETCH_USERS", response.body);
resolve();
})
.catch((error) => {
console.log(error.statusText);
});
});
}
}
ES7: async/await
To get away from callback hell, and to improve asynchronous programming use async function, and you can await on a promise. Code looks much easier to follow (like it is synchronous), but code isn't readable for browsers so you'll need Babel transpiler to run it.
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // wait for actionA to finish
commit('gotOtherData', await getOtherData())
}
}
In my experience, you can skip a few checks if you preset the state with an empty value of the same type as the expected result (if you know what to expect, of course), e.g. if you have an array of items, start with [] instead of null as it won't break v-for directives, .length checks and similar data access attempts.
But generally, adding v-if is a very normal thing to do. There's a section about this in the vue-router documentation and checking whether properties exist or not is exactly what it suggests. Another possible solution it mentions is fetching data inside beforeRouteEnter guard, which assures you will always get to the component with your data already available.
Ultimately, both solutions are correct, and the decision between them is more of a UX/UI question.
I had similar requirements for locations and the google map api. I needed to fetch my locations from the API, load them in a list, and then use those in a map component to create the markers. I fetched the data in a Vuex action with axios, loaded that in my state with a mutation, and then used a getter to retrieve the resulting array in the mounted life cycle hook. This resulted in an empty array as mounted fired before the async action resolved.
I used store.subscribe to solve it this way:
<template>
<div class="google-map" :id="mapName"></div>
</template>
<script>
import GoogleMapsLoader from 'google-maps';
import { mapGetters } from 'vuex';
export default {
name: 'google-map',
props: ['name'],
computed: {
...mapGetters({
locations: 'locations/locations',
}),
},
data() {
return {
mapName: `${this.name}-map`,
};
},
mounted() {
this.$store.subscribe((mutation, state) => {
if (mutation.type === 'locations/SAVE_LOCATIONS') {
GoogleMapsLoader.KEY = 'myKey';
GoogleMapsLoader.load((google) => {
/* eslint-disable no-new */
const map = new google.maps.Map(document.getElementById('locations-map'));
// loop through locations and add markers to map and set map boundaries
const bounds = new google.maps.LatLngBounds();
// I access the resulting locations array via state.module.property
state.locations.locations.forEach((location) => {
new google.maps.Marker({
position: {
lat: location.latitude,
lng: location.longitude,
},
map,
});
bounds.extend({
lat: location.latitude,
lng: location.longitude,
});
});
map.fitBounds(bounds);
});
}
});
},
};