Search code examples
vue.jsvuexrails-api

Error: in Vue consuming Rails Api, data received but Vue can't read


I have a rails api connected to a VueJS front end. I am working on login. When I enter credentials and click login the sign-in method is called and In the Network tab, I see the response, but Vue throws the error:

login error: TypeError: Cannot read property 'auth_token' of undefined

here is the the data returned as seen in the network tab:

{user: {id: 1, email: "[email protected]",…},…}
auth_token: "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MDYwNDU3ODgsImlzcyI6Imlzc3Vlcl9uYW1lIiwiYXVkIjoiY2xpZW50IiwidXNlcl9pZCI6MX0.ZLlKtsdyqS-qFwJljvDsQeBxOJyU756q38-cX6MN_2Q"
user: {id: 1, email: "[email protected]",…}
created_at: "2020-11-10T22:37:01.775Z"
email: "[email protected]"
id: 1
password_digest: "$2a$12$bVmG1cvMidLice0Qcn8sBu36/F1HxhY0NeHT5gRKcAoV8u5Lk5wx6"
updated_at: "2020-11-10T22:37:01.775Z"

Here is my signin method:

   async signin () {
  try {
    console.log('base rute is: ', process.env.VUE_APP_ROOT_API)
    const response = await Api.post('users/login', {
      user: {
        email: this.email_input,
        password: this.password
      }
    })
    const loggedUser = response.data
    console.log('this is login response data: ', loggedUser)
    this.$store.commit('set_token', this.loggedUser.auth_token) [THIS IS WHERE THE ERROR IS THROWN]
    this.$store.commit('set_user', this.loggedUser.user)
    localStorage.setItem('token', this.loggedUser.auth_token)
    localStorage.setItem('user', JSON.stringify(this.loggedUser.user))
    this.$emit('authenticated', true)
  } catch (err) {
    console.log('login error: ', err)
  }
}

}

I am really not sure what the problem is.


Solution

  • You would call this.loggedUser if it was in data. But you have set it as constant.

    async signin () {
      try {
        console.log('base rute is: ', process.env.VUE_APP_ROOT_API)
        const response = await Api.post('users/login', {
          user: {
            email: this.email_input,
            password: this.password
          }
        })
        const loggedUser = response.data
        console.log('this is login response data: ', loggedUser)
        this.$store.commit('set_token', loggedUser.auth_token) 
        this.$store.commit('set_user', loggedUser.user)
        localStorage.setItem('token', loggedUser.auth_token)
        localStorage.setItem('user', JSON.stringify(loggedUser.user))
        this.$emit('authenticated', true)
      } catch (err) {
        console.log('login error: ', err)
      }
      }