I have page '/users'.
export default {
name: 'Users',
created () {
const queryParams = this.$route.query
this[GET_USERS_FROM_SERVER](queryParams)
},
methods: {
...mapActions([GET_USERS_FROM_SERVER]),
onBtnFilterClick () {
this.$route.push('/users?minAge=20&name=alex&withPhoto=true')
}
}
}
When page started, it checks params and gets users from server. But it doesnt work and i think it is because router think that '/users' and '/users?params' is the same path.
If I add this.$router.go() after this.$router.go() it will reload current page and it works. But I want to do it in another way. How can I do this?
Don't reload the page if you do not have to.
this.$route.query can be just as reactive as your other data, so use this fact.
export default {
name: 'Users',
watch: {
'$route.query': {
immediate: true,
deep: true,
handler (queryParams) {
this[GET_USERS_FROM_SERVER](queryParams)
}
}
},
methods: {
...mapActions([GET_USERS_FROM_SERVER]),
onBtnFilterClick () {
this.$route.push('/users?minAge=20&name=alex&withPhoto=true')
}
}
}
When you watch for changes on $route.query, you call this[GET_USERS_FROM_SERVER] whenever it changes. I suspect that this changes the data in your component. I've set the immediate flag to run it when the component is created. I've set the deep flag, because this is an object, and I am not entirely sure if the query object gets replaced with every route change, or just modified. The deep flag will make sure that it will always trigger the handler.
Related
When I dispatch an action in App.vue component in mounted() lifecycle hook, it runs after other components load. I am using async/await in my action and mounted lifecycle hook.
App.vue file
methods: {
...mapActions({
setUsers: "setUsers",
}),
},
async mounted() {
try {
await this.setUsers();
} catch (error) {
if (error) {
console.log(error);
}
}
},
action.js file:
async setUsers(context) {
try {
const response = await axios.get('/get-users');
console.log('setting users');
if (response.data.success) {
context.commit('setUsers', {
data: response.data.data,
});
}
} catch (error) {
if (error) {
throw error;
}
}
},
In Users list component, I need to get users from vuex. So I am using mapGetters to get Users list.
...mapGetters({
getUsers: "getUsers",
}),
mounted() {
console.log(this.getUsers);
},
But the problem is "setting users" console log in running after console logging the this.getUsers.
In Users list component, I can use getUsers in the template but when I try to console log this.getUsers it gives nothing.
How can I run app.vue file before running any other components?
You are using async await correctly in your components. It's important to understand that async await does not hold off the execution of your component, and your component will still render and go through the different lifecycle hooks such as mounted.
What async await does is hold off the execution of the current context, if you're using it inside a function, the code after the await will happen after the promise resolves, and in your case you're using it in the created lifecycle hook, which means that the code inside the mounted lifecycle hook which is a function, will get resolved after the await.
So what you want to do, is to make sure you render a component only when data is received.
Here's how to do it:
If the component is a child component of the parent, you can use v-if, then when the data comes set data to true, like this:
data() {
return {
hasData: false,
}
}
async mounted() {
const users = await fetchUsers()
this.hasData = true;
}
<SomeComponent v-if="hasData" />
If the component is not a child of the parent, you can use a watcher to let you know when the component has rendered. When using watch you can to be careful because it will happen every time a change happens.
A simple rule of thumb is to use watch with variables that don't change often, if the data you're getting is mostly read only you can use the data, if not you can add a property to Vuex such as loadingUsers.
Here's an example of how to do this:
data: {
return {
hasData: false,
}
},
computed: {
isLoading() {
return this.$store.state.app.users;
}
},
watch: {
isLoading(isLoading) {
if (!isLoading) {
this.hasData = true;
}
}
}
<SomeComponent v-if="hasData" />
if you're fetching a data from an API, then it is better to dispatch the action inside of created where the DOM is not yet rendered but you can still use "this" instead of mounted. Here is an example if you're working with Vuex modules:
created() {
this.fetchUsers();
},
methods: {
async fetchUsers() {
await this.$store.dispatch('user/setUsers');
},
},
computed: {
usersGetters() {
// getters here
},
},
Question: Do you expect to run await this.setUsers(); every time when the app is loaded (no matter which page/component is being shown)?
If so, then your App.vue is fine. And in your 'Users list component' it's also fine to use mapGetters to get the values (note it should be in computed). The problem is that you should 'wait' for the setUsers action to complete first, so that your getUsers in the component can have value.
A easy way to fix this is using Conditional Rendering and only renders component when getUsers is defined. Possibly you can add a v-if to your parent component of 'Users list component' and only loads it when v-if="getUsers" is true. Then your mounted logic would also work fine (as the data is already there).
My Nuxt app loads a link and it's child view on the route http://127.0.0.1/user/:id. I put the API calls for the user in mounted hook of the router view.
If route id changes, mounted is not triggered anymore because the child view is already loaded. I ended up with solution - watch the $route.params.id and moved the API call from mounted to this watcher.
watch: {
$route() {
this.getRows()
}
}
Is there a better way to do this?
Solution 1
Force the reload when the route changes defining a :key for the <nuxt-child>, like this:
<nuxt-child :key="$route.fullPath"></nuxt-child>
Solution 2
Put the API call to load the user in a watch to the id coming from the URL instead to mounted, you can use immediate: true to call it in the fist load.
export default {
data() {
return {
user: null
}
},
asyncData({ params }) {
return {
id: params.id
}
},
watch: {
id: {
immediate: true,
handler(id) {
//Call the API to get the user using the id
}
}
}
}
In my parent component:
<UsersList :current-room="current_room" />
In the child component:
export default {
props: {
currentRoom: Object
},
data () {
return {
users: []
}
},
mounted () {
this.$nextTick( async () => {
console.log(this.currentRoom) // this, weirdly, has the data I expect, and id is set to 1
let url = `${process.env.VUE_APP_API_URL}/chat_room/${this.currentRoom.id}/users`
console.log(url) // the result: /api/chat_room/undefined/users
let response = await this.axios.get(url)
this.users = response.data
})
},
}
When I look at the page using vue-devtools, I can see the data appears:
I've run into this issue in the past – as have many others. For whatever reason, you can't rely on props being available in the component's mounted handler. I think it has to do with the point at which mounted() is called within Vue's lifecycle.
I solved my problem by watching the prop and moving my logic from mounted to the watch handler. In your case, you could watch the currentRoom property, and make your api call in the handler:
export default {
props: {
currentRoom: Object
},
data() {
return {
users: []
}
},
watch: {
currentRoom(room) {
this.$nextTick(async() => {
let url = `${process.env.VUE_APP_API_URL}/chat_room/${room.id}/users`
let response = await this.axios.get(url)
this.users = response.data
})
}
},
}
I don't think you really need to use $nextTick() here, but I left it as you had it. You could try taking that out to simplify the code.
By the way, the reason console.log(this.currentRoom); shows you the room ID is because when you pass an object to console.log(), it binds to that object until it is read. So even though the room ID is not available when console.log() is called, it becomes available before you see the result in the console.
There are many use cases for this but the one I'm dealing with is as follows. I have a page with a table, and two data properties, "page" and "filters". When either of these two variables are updated I need to fetch results from the server again.
However, there is no way as far as I can see to watch two variables and react only once, especially in the complicated instance updating filters should reset page to zero.
javascript
data: {
return {
page: 0,
filters: {
searchText: '',
date: ''
}
}
},
watch: {
page (nv) {
this.fetchAPI()
},
filters: {
deep: true,
handler (nv) {
this.page = 0
this.fetchAPI()
}
}
},
methods: {
fetchAPI () {
// fetch data via axios here
}
}
If i update filters, its going to reset page to 0 and call fetchAPI() twice. However this seems like the most intuitive way to have a page with a table in it? filters should reset page to zero as you may be on page 500 and then your filters cause there to only be 1 page worth of results, and a change to either page or filters must call the api again.
Interested to see how others must be tackling this exact same problem reactively?
Take into the rule - watchers are the "last hope". You must not use them until you have other ways.
In your case, you could use events. This way the problem will go by itself:
Add #click="onPageChange" event to the page button (or whatever do you use).
Add #change="onFilterChange" event to the filter component (or whatever do you use). You can also use #click="onFilterChange" with some additional code to detect changes. Still, I am pretty sure you must have something like #change on the filter component.
Then your code will look like:
data: {
return {
page: 0,
filters: {
searchText: '',
date: ''
}
}
},
methods: {
onPageChange () {
this.fetchAPI()
},
onFilterChange () {
this.page = 0
this.fetchAPI()
},
fetchAPI () {
// fetch data via axios here
}
}
In this case, the onFilterChange will change the page data but will not trigger the onPageChange method. So your problem will not exist.
Since the filters object is really complicated and has many options i have decided to keep it on a watcher that triggers setting page to zero and reloading the api. I now solve the problem as stated below. The 'pauseWatcher' data variable is a bit messy and needing to disable it in nextTick seems unideal but its a small price to pay for not having to manually hook up each and every filters input (some of them are far more complex than one input, like a date filter between two dates) and have them each emit onChange events that trigger reloading the api. It seems sad Vuejs doesnt have a lifecycle hook where you can access data properties and perhaps route paramters and make final changes to them before the watchers and computed properties turn on.
data: {
return {
pauseWatcher: true,
page: 0,
filters: {
searchText: '',
date: ''
}
}
},
watch: {
filters: {
deep: true,
handler (nv) {
if (this.pauseWatcher) {
return
}
this.page = 0
this.fetchAPI()
}
}
},
methods: {
fetchAPI () {
// fetch data via axios here
},
goToPage(page) {
this.page = page
this.fetchAPI()
},
decodeFilters () {
// decode filters from base64 URL string
}
},
created () {
this.pauseWatcher = true
this.page = Number(this.$route.query.page) || 0
this.filters = this.decodeFilters(this.$route.query.filters)
this.$nextTick(() => {
this.pauseWatcher = false
})
}
I am using a param, and when I push the param using this.$router.push() it works.
routes: {
path: ':stepId?',
name: 'stepper'
}
BUT, I am also watching $route inside a component in order to catch the value of the param changing (As described in the docs):
watch: {
$route: {
handler: function(to, from) {
const newStepId = (to.params && to.params.stepId) || this.steps[0].id;
const initial = !from;
if (initial || newStepId !== from.params.stepId) {
this.goToStep(newStepId, initial);
}
},
immediate: true
}
}
However when I use the back button, either the to section of the route inside the watch: $route doesn't have any param, just the path OR the watch doesn't even run.
I had the same issue, what worked for me was adding the $watch in the created() method.
created() {
this.$watch("$route",() => {
// this.$route.query is watched now as expected
},
{ immediate: true });
}
Still a bit unclear to me though why putting it in mounted or like what you did doesn't work