'NuxtJS Page is created twice
I am currently facing an Issue in NuxtJS where a method is called twice and a request is therefore sent twice.
This happens in a page and the method which is called twice is created().
I open the page with a parameter like:
http://localhost:3000/mypage?token=123123123
And in the created() Method of the page I call a store dispatch.
created() {
if (this.token === undefined || this.token === null) {
this.$router.push('/login')
} else {
console.log('called created() and sent dispatch')
this.$store.dispatch('thirdPartyLogin', {
token: this.token
})
}
},
The token is parsed via the data property:
data() {
return {
token: this.$nuxt.$route.query.token
}
},
The problem with this is that it is a One Time Token, which means that it is invalid after one use. So after the second call no more success of the request can take place.
Why is the page created twice or created() called twice?
Solution 1:[1]
created() and beforeCreate() are two lifehooks which are called on the server side and client side both. (you will see one console log in your terminal too, because server is firing i)
If you want to do this once you can :
a) use mounted() hook
b) if action needs to be done earlier than mounted u have to use if statement inside created method process.client
. This if statement will check if you are on the client(browser side) if so, do the action
created(){
if(process.client){
//...your action here
}
}
Solution 2:[2]
This is how it works:
Nuxt.js runs created()
once on the server side then on the client side.
The Nuxt SSR
shows the console.log
message of your server and the second console.log
is the message on the client side.
You have 2 Options:
Run this on the serverside:
Wrap it in:
if(process.server){
}
Or run it once on the client side:
if(!process.server){
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | BigKamil5 |
Solution 2 | bill.gates |