how to get the logged in user data in nuxtjs?

731 Views Asked by At

I'm using laravel backend and nuxtjs frontend, when I send a login request I get a response includes the logged in user informations with a token, the response looks like this:

{"message":"success","token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiNzFkYjA1MWM2MTYxMmE4YzAyNWI2YjU3N2xMzJiNzJjMjI0MzRlY2IzNzYwNTg2N2NjOWQ5ZWEwY2MiMJM3uYEiZ8GSlPlQhIctVErO2KzwXOBxifWWoM7et_qT-mgvfsk3ljwiQF9iPQw-WeekBx8J8lcmxDLESa3tfE1Re1Xk2flkcBLmiI4JN2YHh08U1U","user":{"id":1,"role_id":4587,"firstname":"Hans","lastname":"newman","email":"[email protected]","email_verified_at":null,"phone":"89498","skype":"gdgdfg","birthdate":"2021-05-02","address":"asdfaf","postalcode":14984,"city":"jisf","country":"isfisf","status":"mfof","created_at":"2021-06-16T09:33:08.000000Z","updated_at":"2021-06-16T09:39:41.000000Z","image":"1623835988-carlsen.png","description":"sfdgg","geo_lat":5.5,"geo_lng":8.1}}

after logging in I want to redirect the user to his profile page where he can see his data, how can I get the logged in user data from this response.

2

There are 2 best solutions below

0
fevid On

presuming the variable which you are saving response data in is response. you can access the user data via response.user. for accessing any data inside user you can access them further like response.user.id.

Beautified version of your response data for easier read:

{
  "message":"success",
  "token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiNzFkYjA1MWM2MTYxMmE4YzAyNWI2YjU3N2xMzJiNzJjMjI0MzRlY2IzNzYwNTg2N2NjOWQ5ZWEwY2MiMJM3uYEiZ8GSlPlQhIctVErO2KzwXOBxifWWoM7et_qT-mgvfsk3ljwiQF9iPQw-WeekBx8J8lcmxDLESa3tfE1Re1Xk2flkcBLmiI4JN2YHh08U1U",
  "user":{
    "id":1,
    "role_id":4587,
    "firstname":"Hans",
    "lastname":"newman",
    "email":"[email protected]",
    "email_verified_at":null,
    "phone":"89498",
    "skype":"gdgdfg",
    "birthdate":"2021-05-02",
    "address":"asdfaf",
    "postalcode":14984,
    "city":"jisf",
    "country":"isfisf",
    "status":"mfof",
    "created_at":"2021-06-16T09:33:08.000000Z",
    "updated_at":"2021-06-16T09:39:41.000000Z",
    "image":"1623835988-carlsen.png",
    "description":"sfdgg",
    "geo_lat":5.5,
    "geo_lng":8.1
  }
}

if you're redirecting the user, you have to save the response in store so you can use it in another page. unless you are using Auth/Nuxt which saves the data in $auth.

0
dev_mayor On

You can get the user details on the profile page using this.$auth.user which is provided by the nuxt auth module. This returns an array so you can access the actual details of the user using this.$auth.user[0] e.g this.$auth.user[0].email or this.$auth.user[0].firstname etc.

Also if you are using the nuxt module, you can access it using this.$store.state.auth.user.

Check out the nuxt auth module documentation for more info here