How to enable data reactivity on the server? (ssr mode)
-
Hello. I have the following problem: I am trying to get data from my server in this way:
beforeCreate() { this.$store.dispatch('app/getById', this.$route.params.id) }
(I am also tried to do it with preFetch)
The problem is that the data does not come into the app when I try to get the page for the first time after the app starts. When I get the page a second time, I get the data. But, when I change the id, I do not get new data, instead, I get the data corresponding to the previous id. And I need to reload the page again so that the data is updated.I need to get fresh data when I change the id. How can I do this? Help, please.
-
@mazahaler I would bet, that your component is created once and reused later, so when you use beforeCreate handler, the data are reused/not downloaded later. Try with a “mounted” or “beforeMount” handler or other one, whichever will be more suitable in your specific case.
Please look at this helpful diagram:
https://vuejs.org/v2/guide/instance.html#Instance-Lifecycle-HooksAnd one more suggestion: you are making a synchronous call to the server. Maybe this is right, but this stops the rendering (ok, I know you are using SSR) and the “more preferred” way is to communicate with the backend asynchronously.
And #2 please look also here - if your reactivity depends on route change, then maybe this will be the solution:
https://router.vuejs.org/guide/essentials/dynamic-matching.html -
@qyloxe Thanks for the tips. I use beforeCreate and mounted at the same time. beforeCreate is being handled when a user requests a page for the first time and mounted when a user is already on the app and simply goes to different routes.
So far, unfortunately, I have not solved my problem -
@mazahaler and #2 - router watcher? technically it will catch initial page opening, too.
-
@qyloxe I tried
watch: { $route(to, from) { this.$store.dispatch('app/getById', this.$route.params.id) } }
And that hasn’t changed anything
-
@mazahaler said in How to enable data reactivity on the server? (ssr mode):
@qyloxe I tried
And that hasn’t changed anythinghmm, this looks as an error somewhere to me. It should work! Unfortunately, i have almost zero expertise in SSR, maybe this is some SSR quirk.
BUT please do a one another test: There is a technology of navigation guards in vue router:
https://router.vuejs.org/guide/advanced/navigation-guards.html
They could be executed globally or locally, please implement at first a global one, log some info to the console and please check if your route is changed at all! Maybe this is an error?
-
@qyloxe No, that’s not the point. I use router hooks and they work fine.
Nevertheless, thanks for the tips.