E
E
Erik21212019-02-20 20:04:23
Vue.js
Erik2121, 2019-02-20 20:04:23

How to correctly organize the output of user data in Nuxt.js?

Hello everyone, I ran into such a problem when I want to take user data (name, avatar), for example, from localStorage or Cookie, then the data is displayed with a delay, I basically understand why, but not completely, code example in Vuex:
STORE:

import Vue from 'vue'
import Vuex from 'vuex'
import routesapp from '@/static/api'
import axios from 'axios'
import * as Cookie from 'js-cookie'

Vue.use(Vuex)
const store = () => new Vuex.Store({

  state: {
    user: []
  },
  actions: {
    userdata ({
      commit
    }) {
      if (Cookie.length !== 0) {
        commit ('SET_USER', Cookie.get('token'))
      } else {
        axios.get(routesapp.user.id, {params: {id: 20140056}}).then((res) => {
          commit('GET_USER', res.data[0])
        })
      }
    },
    getUserData ({commit, state}, data) {
      state.user = data.storage
    }
  },
  mutations: {
    increment (state) {
      state.counter++
    },
    GET_USER(state, data) {
      state.user = data
      if (state.user.length !== 0) {
        Cookie.set('token', JSON.stringify(data), { expires: 7 })
      }
    },
    SET_USER(state, data) {
      state.user = JSON.parse (data)
    }
  }

})

export default store

COMPONENT:
<template>
  <div class="profile">
    <img :src="userdata.img"
    class="image--cover d-table mx-auto shadow-lg">
    <h3 class="text-center mt-3" style="min-height: 33px">
        {{ userdata.name }}
    </h3>
    <p>{{ userdata.info }}</p>
  </div>
</template>

<script>

import * as Cookie from 'js-cookie'

export default {
  components: {
    
  },
  data() {
    return {
      
    }
  },
  methods: {
    token() {
      return JSON.parse(Cookie.get('token'))
    }
  },
  mounted() {
    if (Cookie.get('token') == null) {
        this.$store.dispatch('userdata')
    }
    this.$store.state.user = this.token()
  },
  computed: {
    userdata() {
      return this.$store.state.user
    }
  },
  created () {
    
  }
}
</script>

That is, everything works, but the data arrives with a small delay, tell me how to make it so that everything is without delay, is caching possible?
I will be grateful for the answer.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Dergachov, 2019-02-21
@vanillathunder

Put in asyncData.

asyncData: {
    if (Cookie.get('token') == null) {
        this.$store.dispatch('userdata')
    }
    this.$store.state.user = this.token();
},
mounted: {}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question