4

I am trying to send surveyjs results to my API.

In mounted(), I make a GET request with vue-resource, get questions from my dB and then set surveyjs. To send the results, I tried to use this.$http.post, in the surveyJS onComplete function, but I got Cannot read property 'post' of undefined. Also, I tried to put a watch on the result variable, but it did not work.

mounted() {
    this.$http
      .get("myAPI")
      .then(res => res.json())
      .then(questions => {
        this.questions = questions;
        this.survey = new SurveyVue.Model(this.questions.pesquisa);
        this.survey.locale = "pt";

        this.survey.onComplete.add(function(survey) {
          this.result = survey.data;
          this.$http
          .post(
            `myAPI`,
            this.result,
            { headers: { "Content-Type": "application/json" } }
          )
          .then(response => {
            console.log(response);
            UIkit.notification({
              message: "Success",
              pos: "top-center",
              status: "success"
            });
          })
          .catch(error => {
            console.log(error);
            UIkit.notification({
              message: "Erro",
              pos: "top-center",
              status: "danger"
            });
          });
        }); 
      })
      .catch(error => {
        console.log(error);
        UIkit.notification({
          message: "Error",
          pos: "top-center",
          status: "danger"
        });
      });
}
victor
  • 75
  • 1
  • 7

1 Answers1

7

To get access to this inside the onComplete.add()'s parameter, you could replace your regular function with an arrow function:

this.survey.onComplete.add(survey => {
  this.result = survey.data;
  /* rest of your code... */
})

An alternative is to place this into a variable, which can be used to access the outer this:

const that = this;
this.survey.onComplete.add(function(survey) {
  that.result = survey.data;
  /* rest of your code... */
})

Read more about this.

The gist of it is that inside the the function, the function's this overrides the component's this, unless it's an arrow function, which purposefully doesn't have a this so the outside one is available.

tao
  • 82,996
  • 16
  • 114
  • 150