Home > OS >  Cannot read properties of undefined (reading 'elements') at VueComponent.mounted vue-strip
Cannot read properties of undefined (reading 'elements') at VueComponent.mounted vue-strip

Time:06-25

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

CodePudding user response:

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.

CodePudding user response:

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