vue.jsaxiosobservableelectron-vue

Vue.js with Axios use data from other method


I have a external api which returns a json of a user with some attributes like username. I want to use this username in my vue methods as a url parameter and defined the function getUser(). My problem is that the parameter keeps undefined

Here is my code

<script>
import Axios from 'axios-observable'
export default {
  data () {
    return {
      appointments: {},
      event_counter: 0,
      user: ''
  },
  methods: {
    getUser: function () {
      Axios
        .get('http://127.0.0.1:5000/users/get_user')
        .subscribe(response => { this.user = response.data.username })
    },
    getAppointments: function () {
      Axios
        .get('http://127.0.0.1:5000/appointments/get_appointments?user=' + this.user)
        .subscribe(response => { this.appointments = response.data })
    },
    fetchData: function () {
      setInterval(() => {
        this.getAppointments()
      }, 150000)
    }
  },
  mounted () {
    //this.user = this.getUser()
    this.getUser()
    this.fetchData()
  },
  created () {
    //this.user = this.getUser()
    this.getUser()
    this.getAppointments()
  }
}
</script>

I tried some variants with return response.data or data: this.getUser() etc. Obtaining the user in template with {{ user }} works fine but isn't helpful. I don't have any syntax or runtime error from vue/electron-vue

Any idea?


Solution

  • Finally got a solution!

    <script>
    import Axios from 'axios'
    export default {
      data () {
        return {
          appointments: {},
          event_counter: 0,
          user: 'test'
        }
      },
      methods: {
        getUser: function () {
          return Axios
            .get('http://127.0.0.1:5000/users/get_user')
            .then(response => {
              this.user = response.data.username
              return this.user
            })
        },
        getAppointments: function () {
          this.getUser()
            .then(data => {
              let url = 'http://127.0.0.1:5000/appointments/get_appointments?user=' + data
              Axios
                .get(url)
                .then(response => { this.appointments = response.data })
            })
        },
        fetchData: function () {
          setInterval(() => {
            this.getAppointments()
          }, 150000)
        }
      },
      mounted () {
        this.fetchData()
      },
      created () {
        this.getAppointments()
      }
    }
    </script>
    

    The solution was to change the call of the getUser() and retrieve the date in the arrow function block .then(data =>). The answer of @loan in this Issue give me the hint: How to set variable outside axios get.

    Thanks a lot to all.