The Vuex this.$store is not defined in the "mounted" lifecycle hook of the component

Currently in the process of integrating Paypal into my Vue project, following the official documentation and copying the necessary code from here. Successfully rendered the Paypal button, completed the transaction, and obtained an orderID. However, encountering an issue when trying to send the orderID to my server due to the error message: 'this.$store is undefined'. Interestingly, I was able to reference this.$store in other components without any trouble. Here is the snippet of my code:

Update: Attempted to console.log(this) within the onApprove method which returned undefined. Could this be the root of the problem?

Update: Changed the OnApprove method and capture() method to arrow functions, resulting in a new error message of 'this.$store.dispatch(...).then(...).err' not being recognized as a function.

Update: Resolved the previous error by switching .err() to .catch().

Update: Encountered another issue where clicking on the Paypal button sometimes causes the external Paypal window to close abruptly. Have to click multiple times to prevent this unexpected behavior. Upon inspecting the console log, came across the error message depicted in the screenshot below.

https://i.sstatic.net/AIBc0.png

    <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>

Successfully received the orderID indicating a successful transaction, but dealing with the undefined this.$store obstacle preventing the order ID from reaching the server.

https://i.sstatic.net/z4Oxv.png

Answer №1

To ensure access to this, implement an arrow function in your callback function.

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for altering a key within a tree-view:

I am working with a potentially infinite tree-view array: type Tree = { id: number; name: string; email: string; children: Tree[]; }; const tree: Tree[] = [ { id: 1, name: 'Truck', email: '@mail', children ...

The difference between emitting and passing functions as props in Vue

Imagine having a versatile button component that is utilized in various other components. Instead of tying the child components to specific functionalities triggered by this button, you want to keep those logics flexible and customizable within each compon ...

The Bootstrap/Angular tab list items are generated dynamically based on the API response, leading to issues with the DOM

In one of my Angular templates, I have the following snippet. It consists of Bootstrap 3 tabs, but the tab list items (links) are generated dynamically after receiving a response from the API. <ul class="nav nav-tabs pull-right" role="tablist"> &l ...

unable to retrieve the li element's ID when clicked

I am working on a code snippet to display tabs with dynamic content. $start = strtotime($_GET['date']); $dates = array(); for ($i = 0; $i <= 7; $i++) { $date = date('Y-m-d', strtotime("+$i day", $start)); $date1 = $ ...

Form validation is an essential feature of the Angular2 template-driven sub form component

I'm currently working on a template-driven form that includes a group of inputs generated through an ngFor. My goal is to separate this repeating 'sub-group' into its own child component. However, I'm encountering difficulties in ensur ...

Receiving the final outcome of a promise as a returned value

Seeking to deepen my comprehension of promises. In this code snippet, I am working on creating two promises that will return the numbers 19 and 23 respectively. However, when attempting to console log the value returned from the first promise, I encounte ...

How can I fetch data from SQL using JavaScript based on a specific value in PHP?

My application is built using the Yii2 framework. Within my application, there is a view.php file that consists of an element and a button. The element, <div id="userId">, contains the user's login ID, and I aim to use the button to re ...

Having trouble sending a function as a prop to a child component in React

Something odd is happening, I'm confident that the syntax is correct, but an error keeps popping up: Error: chooseMessage is not a function // MAIN COMPONENT import React, { useState } from 'react' export default function LayoutMain(prop ...

Transforming PHP Variable Using Ajax

I have a variable called $type and I need it to be either month or year. This change should occur when a div is clicked. I attempted to use an onclick event with an ajax call. The ajax call and the variable are both in the same script (index.php). Within ...

Code is not running in ReactJS

My challenge is to use canvas and script to draw a rectangle with one diagonal line. However, when I try to do so, only the rectangle appears on my browser. It seems like the script is not being executed. Here's the code: import React, { Component } ...

Using jQuery ajax links may either be effective or ineffective, depending on the scenario. At times

Can someone please assist me in understanding why an ajax link may or may not work when clicked? It seems to function intermittently. window.onload = function(){ function getXmlHttp(){ ...... // simply ajax } var contentContainer = ...

Having trouble integrating the circular progress bar into the movie card and getting it to align properly

Struggling to position my react circular bar for movie rating in the bottom corner of the movie card. The classes are not working as expected, even though I tried to replicate it from another website using React and SCSS while I'm utilizing Material-U ...

You may encounter an error stating "Property X does not exist on type 'Vue'" when attempting to access somePropOrMethod on this.$parent or this.$root in your code

When using VueJS with TypeScript, trying to access a property or method using this.$parent.somePropOrMethod or this.$root.somePropOrMethod can lead to a type error stating that Property somePropOrMethod does not exist on type 'Vue' The defined i ...

Building the logic context using NodeJS, SocketIO, and Express for development

Exploring the world of Express and SocketIO has been quite an eye-opener for me. It's surprising how most examples you come across simply involve transmitting a "Hello" directly from app.js. However, reality is far more complex than that. I've hi ...

The Npm generate script is failing to create the necessary routes

I've integrated vue-router into my nuxt project, but I encountered an issue when running npm run generate - it generates everything except for my pages. I suspect the problem lies with the router implementation as I didn't face any issues before ...

Tips for extracting and utilizing a JSON object provided by the parent page:

Sorry in advance if this question has already been addressed. I've spent hours searching on Google, but haven't found a satisfactory answer yet. Below is the code snippet I'm working with: <ion-content> <div class="list"> ...

Leverage the LatLng retrieved from autocomplete to locate a nearby destination with the help of vue-google

Having an autocomplete feature on my landing page allows me to collect user address details like latitude, longitude, and address. After capturing these details, I store them using the following commit method: locate ({commit}, payload) { commit(&a ...

The issue with the AngularJS filter seems to be arising specifically when applied to

My AngularJS filter isn't functioning properly when used with an Object. Here's the View: <input type="text" ng-model="searchKeyUser.$" placeholder="Search Keys" class="form-control"><br> <ul class="list-group"> <li cla ...

Sending data in chunks using Vue.js

I'm interested in sending the data in chunks. Currently, what I send to the server looks like this: for loop - 1, 2, 3. However, the server receives it asynchronously as 3, 1, 2 and I need it to be received synchronously in the order of my for loop: 1 ...

Generating random indexes for the Answer button to render

How can we ensure that the correct button within the Question component is not always rendered first among the mapped incorrect buttons for each question? Is there a way to randomize the positions of both correct and incorrect answers when displaying them, ...