Issaki
Issaki

Reputation: 1064

Vuex this.$store undefined in "mounted" life cycle hook

I am currently integrating the Paypal service to my Vue project. I've referred to the official document and copied the code https://developer.paypal.com/docs/checkout/integrate/#6-verify-the-transaction. I was able to render the Paypal button, complete the transaction and receive an orderID. However, I am unable to send the orderID to my server due to the following error: this.$store is undefined. Do note that, I was able to reference this.$store in my other components. Below is my following code:

Update: I tried to console.log(this) in the onApprove method and it returns undefined. Is that the problem?

Update I've converted the OnApprove method and capture() method to arrow function and received a different error message this.$store.dispatch(...).then(...).err is not a function

Update I managed to fix the above error by changing .err() to .catch().

Update I faced another problem, sometimes which I click on the Paypal button, the external Paypal window will immediately close by itself. I have to click on the button a few time, to prevent this strange behaviour. I went to the console log and found this message as shown in the following screenshot.

enter image description here

    <template>
  <div>
    <div id="paypal-button-container"></div>
  </div>
</template>

<script>
import { PRODUCT_PAYPAL } from "@/store/actions/products";

export default {
  mounted() {
    paypal
      .Buttons({
        createOrder: function(data, actions) {
          return actions.order.create({
            purchase_units: [
              {
                amount: {
                  value: "0.01"
                }
              }
            ]
          });
        },
         onApprove: (data, actions) => {
          return actions.order.capture().then(details => {
            alert("Transaction completed by " + details.payer.name.given_name);
            console.log("orderID is ");
            console.log(data.orderID);

            // Call your server to save the transaction
            return this.$store
              .dispatch(PRODUCT_PAYPAL, data.orderID)
              .then(() => {
                alert("success");
              })
              .catch(() => {
                alert("error");
              });
          });
        }
      })
      .render("#paypal-button-container");
  }
};
</script>

<style>
</style>

As shown in the following screenshot, I was able to receive the orderID which means that the transaction was successful. However, this.$store is undefined. Hence, I can't send the order ID to my server

enter image description here

Upvotes: 0

Views: 960

Answers (1)

Kris D. J.
Kris D. J.

Reputation: 72

Use an arrow function on your callback function, to have access to this.

onApprove: (data, actions) => ...

return actions.order.capture().then((details) => ...

Upvotes: 1

Related Questions