What is the process for assigning a variable within a callback function?

Having trouble with assigning the dat.id received in a callback to my AccuprobeID variable, which is used for another API call later on. Any assistance would be greatly appreciated. I attempted changing sap.deviceInfo(callback) to

sap.deviceInfo().then(res=>{})
but unfortunately that did not work :/

<template>
  <div class="home">
        <b-button v-if="!claimCode.length>0" @click="createClaim">claim</b-button>
        <div v-if="claimCode.length>0 && !claimCodeSet">
          <p>Please Switch Network to Photon </p>
           <b-button variant="primary"  @click="addClaim(claimCode)">Add Claim Code to Accuprobe</b-button>
        </div>
        <div v-if="claimCodeSet">
            Please Switch Back to Normal Network
            <b-button @click="claimDeviceToProduct">Claim to Account</b-button>
        </div>
  </div>
</template>

<script>
import axios from 'axios'
var SoftAPSetup = require('softap-setup');
var sap = new SoftAPSetup();
 var Particle = require('particle-api-js');
var particle = new Particle();
var token;
export default {
  data(){
    return{
      claimCode:'',
      claimCodeSet:false,
      AccuprobeID:''
    }
  },
  name: 'home',
  components: {
  },
  methods:{
    createClaim(){
      axios.post('https://api.particle.io/v1/products/2121/device_claims/?access_token='+this.$store.state.user.PToken)
      .then((res)=>{
        console.log(res)
        this.claimCode=res.data.claim_code
        console.log(this.claimCode)})
    },
    addClaim(claimCode,AccuprobeID){ 
      sap.deviceInfo(callback);
      function callback(err, dat) {
        if (err) { throw err; }
        console.log("Device ID: %s, claimed: %s", dat.id, dat.claimed ? "yes" : "no");
         AccuprobeID=dat.id
         return AccuprobeID
      };
        sap.setClaimCode(claimCode,callback);
        function callback(err, dat) {
          if(err) { throw err; }
          }
          this.claimCodeSet=true
        },
      claimDeviceToProduct(AccuprobeID){
        console.log(AccuprobeID)
        particle.addDeviceToProduct({product:'2121', deviceId: AccuprobeID, auth: this.$store.state.user.Bear }).then(function(data) {
          console.log('device claim data:', data);
        }, function(err) {
          console.log('device claim err:', err);
        });
      },
  }}
</script>

Answer №1

Accessing Local Data in Vue using this.data_name

In order to access local data within Vue components, it is important to note that you need to create a new variable reference to this outside of certain functions, as the context of this may refer to the global scope.

addClaim(claimCode){
 var self = this;
 sap.deviceInfo(function callback(err, dat) {
   if (err) { throw err; }
   console.log("Device ID: %s, claimed: %s", dat.id, dat.claimed ? "yes" : "no");
   self.AccuprobeID = dat.id
 });
 sap.setClaimCode(claimCode, function callback(err, dat) {
   if(err) { throw err; }
 });

 this.claimCodeSet = true
}

Alternatively, you can use arrow functions to directly access this.

addClaim(claimCode){
 sap.deviceInfo((err, dat) => {
   if (err) { throw err; }
   console.log("Device ID: %s, claimed: %s", dat.id, dat.claimed ? "yes" : "no");
   this.AccuprobeID = dat.id
 });
 sap.setClaimCode(claimCode, (err, dat) => {
   if(err) { throw err; }
 });

 this.claimCodeSet = true
}

Read more about JavaScript variable scope and 'this'

Answer №2

You must utilize the AccuprobeID that has been defined in the data. To access it, you will need to use this.AccuprobeID.

Below is the code snippet:

<template>
  <div class="home">
        <b-button v-if="!claimCode.length>0" @click="createClaim">claim</b-button>
        <div v-if="claimCode.length>0 && !claimCodeSet">
          <p>Please Switch Network to Photon </p>
           <b-button variant="primary"  @click="addClaim(claimCode)">Add Claim Code to Accuprobe</b-button>
        </div>
        <div v-if="claimCodeSet">
            Please Switch Back to Normal Network
            <b-button @click="claimDeviceToProduct">Claim to Account</b-button>
        </div>
  </div>
</template>

<script>
import axios from 'axios'
var SoftAPSetup = require('softap-setup');
var sap = new SoftAPSetup();
 var Particle = require('particle-api-js');
var particle = new Particle();
var token;
export default {
  data(){
    return{
      claimCode:'',
      claimCodeSet:false,
      AccuprobeID:''
    }
  },
  name: 'home',
  components: {
  },
  methods:{
    createClaim(){
      axios.post('https://api.particle.io/v1/products/2121/device_claims/?access_token='+this.$store.state.user.PToken)
      .then((res)=>{
        console.log(res)
        this.claimCode=res.data.claim_code;
        console.log(this.claimCode)})
    },
    addClaim(claimCode){
      sap.deviceInfo(callback);
      function callback(err, dat) {
        if (err) { throw err; }
        console.log("Device ID: %s, claimed: %s", dat.id, dat.claimed ? "yes" : "no");
         this.AccuprobeID=dat.id;
      };
      sap.setClaimCode(claimCode,callback);
      function callback(err, dat) {
        if(err) { throw err; }
        }
      this.claimCodeSet=true;
    },
    claimDeviceToProduct(){
      console.log(this.AccuprobeID)
      particle.addDeviceToProduct({product:'2121', deviceId: this.AccuprobeID, auth: this.$store.state.user.Bear }).then(function(data) {
        console.log('device claim data:', data);
      }, function(err) {
        console.log('device claim err:', err);
      });
    },
  }}
</script>

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

Animating elements within a D3.js force layout

I am looking to create a unique data visualization that resembles floating bubbles with text inside each bubble. Currently, I have a prototype using mock data available here: JSfiddle // Here lies the code snippet // ... However, my current challenge li ...

Issue encountered when relocating an element to the bottom of its containing parent

Is there a way to effectively relocate an element to the bottom of its parent container? While I found some discussions on this topic, such as this one and that one, I am facing an issue with my specific element that has a scroll bar. Using methods like ...

Conceal all columns apart from the first when expanding/collapsing a table using

I have a table with a single header and multiple columns, and I am trying to implement an expand/collapse feature based on header clicks using the code snippet below: $(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100 ...

Struggling to make vue-i18n function properly with nuxt generate?

In an effort to enhance my skills, I am creating a small Nuxt project from scratch. While the project runs smoothly on the local server, I have encountered an issue with the language switcher not updating the translation fields when using nuxt generate. U ...

What are the best methods for obtaining live data for my web application?

In my current project, I have developed an HTML5 web application that displays various icons on Google Maps. The front-end is built with AngularJS and JavaScript, while the backend consists of a WebAPI, Entity Framework, and SQL database. At the moment, t ...

What is a creative way to store and organize ids along with their sub ids in an object without relying on arrays?

Currently, I am faced with the challenge of sending data to the server that contains multiple ids with sub ids. I have been utilizing arrays to handle this, but the repetitive use of find() and findIndex() functions in the DOM (specifically with Vue) is st ...

How is it possible for the igx-expansion-panel to close when there is a nested angular accordion present?

Currently, I am faced with the challenge of closing the igx-expansion-panel within my Angular project. While everything functions smoothly with a standard panel, things get a bit tricky when dealing with nested angular accordion structures using igx-accord ...

Locate and dismiss a toast message (Toastr)

I have a webpage where I can add multiple popup notifications called toasts dynamically using the toastr plugin found at https://github.com/CodeSeven/toastr. Each toast has an Ok link that, when clicked, should only close that specific toast and not all v ...

Shifted picture next to the accompanying words

I have successfully created a slideshow of images using JavaScript. <html> <head> <script language="JavaScript"> var i = 0; var path = new Array(); path[0] = "one.jpg"; path[1] = "two.jpg"; function swapImage() { document.slide ...

Link components in Next.js now automatically add the current path when working with nested dynamic routes, making it

How can I effectively handle nested dynamic routes and utilize the Next.js Link component? Let's say I have 2 different file paths: /pages/projects/index.js <Link href={`/projects/${project.id}`} key={index}> <a>Project Name</a> ...

The horizontal scroll menu transition in CSS is choppy and lacks smoothness

My goal is to create a seamless transition for the menu. However, when clicking the arrows, the 2nd div appears at the bottom of the 1st div, causing a choppy effect. Below is the code I am currently using: To view my code, please visit: ...

Display the username on a Meteor React component

I'm facing an issue with one of my React components, which serves as the main layout for my application. It includes a navigation bar that displays the username of the currently logged-in user. The problem arises when Meteor.user() returns undefined d ...

Store the result of an EJS include tag in a JavaScript variable

I have my footer HTML contained in the file named footer.ejs. I am looking to add this HTML dynamically to another page using JavaScript. The following code snippet does not seem to be functioning properly. Is there a way to store a template output in a J ...

Incorporating a dropdown feature into the navigation bar

Greetings, I am currently learning on the job as I work on a new website for my family business. I am struggling to make the drop-down navigation menu function properly on both desktop and mobile. I want it to have a simple design similar to the main nav ...

Ways to identify if the text entered in a text area is right-to-left justified

Within a textarea, users can input text in English (or any other left-to-right language) or in a right-to-left language. If the user types in a right-to-left language, they must press Right-shift + ctrl to align the text to the right. However, on modern O ...

CASL user update has been refreshed

My CASL implementation is quite basic and I've noticed that the documentation lacks detail. The code I'm using is essentially a copy-paste from the docs: import { abilitiesPlugin } from '@casl/vue' import defineAbilitiesFor from &apos ...

Retrieving information from an object using JavaScript

Hello, I am facing a challenge with extracting data from an object via a web API in ReactJS. It seems like the data returned by the API is not structured properly as a JavaScript object. To view the issue directly in your browser visit: I need assistance ...

Utilizing multiple Vue.js 3 plugins for enhanced functionality

Is there a way to utilize multiple plugins in vuejs 3? import { createApp } from 'vue' import App from './App.vue' import router from './router' import axios from 'axios' import Antd from 'ant-design-vue'; ...

The use of ExpressJs res.sendFile is not effective following the implementation of middleware

Currently, my focus is on mastering JWT and its implementation in Node.js with Express. I've developed a middleware that aims to authenticate users using a token: app.use(function(req, res, next) { if(req.headers.cookie) { var authentication = req.h ...

Connect a function to create a new document element in order to modify the

I am attempting to intercept document.createElement in order to modify the value of the src property for each assignment. My current approach involves: var original = document.createElement; document.createElement = function (tag) { var element ...