i've a vue app which uses stripe as payment but each time i refresh i get
Cannot read properties of undefined (reading 'elements')
this the error i get in my console
Error in mounted hook: "TypeError: Cannot read properties of undefined (reading 'elements')"
this is my script tag on how i call my stripe payment
<script>
export default {
data() {
return {
error: "",
stripe: null,
card: null
};
},
computed: {
...mapGetters([
"getCart",
])
},
mounted() {
this.stripe = Stripe("pk_test_51KGqWkHC");
let elements = this.stripe.elements();
this.card = elements.create("card");
this.card.mount(this.$refs.card);
},
methods: {
async onPurchase() {
try {
let token = stripe.createToken(this.card);
let response = axios.post("http://localhost:5000/api/pay", {
token: token,
totalPrice: this.getCartTotalPriceWithShipping,
cart: this.getCart,
estimatedDelivery: this.getEstimatedDelivery
});
if (response.success) {
// Do something like redirecting to the home page
this.$store.commit("clearCart");
this.$router.push("/");
}
} catch (err) {
console.log(err);
}
},
}
};
</script>
I use this in my nuxt js project and it works fine,
please what i'm i doing wrong in vue
this.stripe.elements();
returns undefined, probably this is not working:
Stripe("pk_test_51KGqWkHC");
check that the initialization string you are using is correct.
Otherwise, check the docs.
if its undefined, you can handle this error:
mounted() {
this.stripe = Stripe("pk_test_51KGqWkHC");
if(this.stripe.elements) {
let elements = this.stripe.elements();
this.card = elements.create("card");
this.card.mount(this.$refs.card);
}
},
But seeing your whole code, you have some inconsistencies:
Im not sure how you're supposed to access to Stripe(), if you don't have imported it. Maybe it's a module?
Stripe("pk_test_51KGqWkHC") -> this.$stripe("pk_test_51KGqWkHC")
Then in let token = stripe.createToken(this.card);
stripe doesn't exists in async onPurchase(), so how do you have access to it?
This should be this.stripe.createToken(this.card) or this.$stripe.createToken(this.card) if Stripe is injected on Vue.
Related
Currently I have following Watches in Product.vue file
watch: {
isOnline: {
async handler (isOnline) {
if (isOnline) {
const maxQuantity = await this.getQuantity();
this.maxQuantity = maxQuantity;
}
}
},
isMicrocartOpen: {
async handler (isOpen) {
if (isOpen) {
const maxQuantity = await this.getQuantity();
this.maxQuantity = maxQuantity;
}
},
immediate: true
},
isSample (curr, old) {
if (curr !== old) {
if (!curr) {
console.log('send the updateCall', curr);
// this.updateProductQty(this.product.qty);
pullCartSync(this);
}
}
}
}
but I am getting this following error (Vue Warn) in console
[Vue warn]: Method "watch" has type "object" in the component definition. Did you reference the function correctly?
I'm not sure why i am getting this error, as the syntax i am using seems to be correct, and its even functioning right.
Any suggestions why its giving this warning in error console?
Update:
Location where i have used the watch in vue page.
You have something like methods: { watch: {} } in your component definition. That's why vue is complaining. That might be added by a mixin as well.
so I'm trying to get my Axios to do a get request with a param that'll end the url in
'/?user= {id}'
the id is passed in by my loggedInUser.id from Vuex. I know that async functions won't accept 'this' inside the call so I included store as a parameter. Something's still off with how I passed the data around thought I think. Would appreciate any help, thanks!
import { mapGetters } from "vuex";
export default {
computed: {
...mapGetters(["loggedInUser"])
},
head() {
return {
title: "Actors list"
};
},
components: {
EditProfile
},
async asyncData({ store }) {
try {
const body = { data: store.getters.loggedInUser.id };
const { actors } = await $axios.$get(`/api/v1/actors/`, {
params: {
user: body
}
});
return { actors };
} catch (e) {
return { actors: [] };
}
},
data() {
return {
actors: []
};
Edit
I got it to work when I removed the data: from 'const body' and removed the brackets as well around 'actor'
try {
const body = store.getters.loggedInUser.id;
const actors = await $axios.$get(`/api/v1/actors/`, {
params: {
user: body
}
});
You can access your params from Context.
Context is available in special nuxt lifecycle areas like asyncData, fetch, plugins, middleware and nuxtServerInit.
In Nuxt, with asyncData hook you can get query parameters from the route context key.
Please read the Nuxt.js Context documentation. The context provides additional objects/params from Nuxt to Vue components
With your-domain/?user=wonderman
asyncData({ route: { query: queryParams} }) {},
variable queryParams is an object:
{ user: "wonderman" }
Google translate in vue is throwing below the exemption
vue.esm.js?efeb:1897 TypeError: google.translate.TranslateElement is not a constructor
Here is my code, is there anything I am missing?
Javascript
created () {
this.loadDropdown();
window.google = document.createElement('script');
google.setAttribute('src',"//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit");
document.head.appendChild(google);
this.googleTranslateElementInit();
}
methods: {
googleTranslateElementInit() {
new google.translate.TranslateElement(
{pageLanguage: 'en'},
'google_translate_element'
);
},
},
Template
<div class="google_translate" id="google_translate_element"></div>
jsonp callback must be global(window) scope.
u can try this:
methods: {
createJsonpCallback() {
window.googleTranslateElementInit() {
new google.translate.TranslateElement(
{pageLanguage: 'en'},
'google_translate_element'
);
},
}
},
My API url is http://localhost:5000/api/user/list, data shows as:
[{"Id":1,"name":"Michael","pwd":"123456","age":0,"birth":"2018-01-05","addr":"''"},{"Id":2,"name":"Jack","pwd":"123512616","age":0,"birth":"2018-01-05","addr":"''"}]
User.vue
import axios from 'axios';
export default {
data() {
return {
filters: {
name: ''
},
loading: false,
users: [
]
}
},
methods: {
getUser: function () {
axios.get('http://localhost:5000/api/user/list', function (data) {
this.$set('users', data);
})
}
},
mounted() {
this.getUser();
}
});
The error is :
Unhandled promise rejection Error: Request failed with status code 404(…)
How can I fix it?
You should register a handler for your axios request.
Currently you are using settings argument as a handler.
axios.get('http://localhost:5000/api/user/list').then(function (response) {
// this is your handler.
})
Btw, make sure you are not requesting via CORS.
In my case there was a spelling mistake in URL string. It is fixed after that correction.
I have a products component and a product owner component. Each Product will have an owner
What I am trying to do
I am receiving a list of products by calling an API endpoint. When the promise is resolved, I have a list of Products. Each Product has an OwnerID. I am trying to call another API Endpoint to fetch the name of the owner and assign it to the current product being iterated.
My Code so far
<script>
var config = require('../config');
export default {
data () {
return {
products: [],
}
},
ready () {
this.getProducts().then(t => {
console.log(t);
});
},
methods : {
getProducts : function() {
let url = config.API.GetProduct
this.$http.get(url).then(response=> {
this.products = response.data.resource;
var p = this.products.map(this.getOwner);
return Promise.all(p);
}, error=> {
console.error("An error happened!")
});
},
getOwner : function(product) {
let url = config.API.GetProductOwnerName.replace('[$$$]', product.OwnerID);
var p = new Promise();
this.$http.get(url).then(response => {
product.OwnerID = response.data.resource[0].OwnerName;
p.resolve(currentObj);
});
return p;
}
}
components: {}
}
</script>
Error that I am facing
Now whenever I am trying to do that, I keep getting the following errors
Uncaught TypeError: Cannot read property 'then' of undefined
Uncaught (in promise) TypeError: Promise resolver undefined is not a function(…)
Can somebody please let me know what I am doing wrong here ?
Thanks
You don't have to recreate a new promise object. You can just return the object you want to be passed to the next call.
getProducts: function() {
let url = config.API.GetProduct
return this.$http.get(url).then(response => {
this.products = response.data.resource;
return this.products.map(this.getOwner);
}, error=> {
console.error("An error happened!")
});
},