0

For some reason this was giving me trouble this morning, and I just couldn't figure out why it wouldn't work.

I have a variable 'applications' set equal to the data returned by my axios call. I want to include 'applications.name' as a field in my data() to send as a form. However when I try this, Vue gives me an error saying 'Cannot read property 'name' of undefined'.

{{applicants.name}} and {{applicants.role}} are working in the template, so I'm not just getting empty data

Also another thing, data() doesn't seem to recognize my 'this.loggedInUser.id' field either for some reason. (I've imported both Vuex and mapGetters)

Appreciate the help! :)

async asyncData({ $axios, params }) {
    try {
      let applicants = await $axios.$get(`/api/v1/apps/${params.id}/`);
      return { applicants };
    } catch (error) {
      console.log(error);
      return { applicants: [] };
    }
  },
data() {
    return {
      applicants: [],
      application: {
        name: this.applicants.name,
        status: null,
        company: null,
        role: this.applicants.role
        // user: this.loggedInUser.id

      }
    };
  }
};

2 Answers 2

2

Try to pass this as parameter to the data property function:


data(vm) { //refers to this keyword
    return {
      applicants: [],
      application: {
        name: vm.applicants.name,
        status: null,
        company: null,
        role: vm.applicants.role
        // user:vm.loggedInUser.id

      }
    };
  }

or make application as a computed property :

data() {
    return {
      applicants: [],
    
    };
  }
,
computed:{
    application(){
        return {
        name: this.applicants.name,
        status: null,
        company: null,
        role: this.applicants.role
        // user: this.loggedInUser.id

      }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

The computed property solution worked for me, would you mind just explaining why variables can also be stored in Computed? I can only find docs on it showing methods that manipulate variables in data(). Thanks!
if that data depends on other data it should be stored as computed property, if it doesn't it could be declared in data option
0

I am assuming that when the data is initialized, the values applicants.name and loggedInUser.id do not exist. Try changing the data like this

data() {
    return {
        applicants: { name: '' },
        application: {
            name: this.applicants.name,
        },
        loggedInUser: { id: '' }
    };
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.