msh
msh

Reputation: 21

how to Get user information from vuejs with axios?

Please advise what exactly I should write instead of this phrase? To display receive user information from the database? after logging in

//ProfileDropDown.vue
<template>
  <div class="text-right leading-tight hidden sm:block">
    <p class="font-semibold">{{ activeUserInfo.displayName }}</p>
    <small>Available</small>
  </div>
</template>

<script>

export default {
  data () {
    return {
       activeUserInfo: null
    }
  },
  methods: {
    async getUserInfo () {
      try {
           const res = await (write get request with axios to api)
           this.activeUserInfo = (object from res)
      } catch (e) {}
    }
  },
  async created() {
     await this.getUserInfo();
  }
}
</script>
If you want get data with store, you can use axios in state.js

...
const getUserInfo = () => {
  const userInfo = {}

  try {
      const res = await (write get request with axios to api)
      userInfo = (object from res)
  } catch (e) {}

  return userInfo
}
...

What exactly should I write instead of this phrase? "write get request with axios to api" "object from res"

Upvotes: 1

Views: 1544

Answers (1)

kissu
kissu

Reputation: 46676

This is how to use the API named jsonplaceholder to fetch 10 users in a /pages/index.vue

<template>
  <div>
    Here is how the received payload is looking (Array of Objects)
    <pre>{{ users }}</pre>
    <div>
      -------------
      <p v-for="user in users" :key="user.id">
        name: <span>{{ user.name }}</span> and email: {{ user.email }}
      </p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      users: [],
    }
  },
  async fetch() {
    // $get is a shortcut for `.data` as shown here: https://axios.nuxtjs.org/usage#-shortcuts
    const usersResult = await this.$axios.$get('https://jsonplaceholder.typicode.com/users')
    console.log('what we have received', usersResult)
    this.users = usersResult
  },
}
</script>

You can found an example repo on this github link: https://github.com/kissu/so-nuxt-how-to-use-axios


Also, prefer using fetch() hook, or asyncData() since you're in a Nuxt context and not only Vue. More info can be found here: Difference between Asyncdata vs Fetch

Upvotes: 1

Related Questions