B
B
betterthanyouthink2020-10-21 11:40:28
Vue.js
betterthanyouthink, 2020-10-21 11:40:28

How to properly get and display data from the server in vue/vuex?

I have a user in state which is null by default

state: {
 user: null
}


User information will be contained in many places on the site, so the request must be made as early as possible. Where is the best place to do it? I do like this in App.vue:

created() {
        this.$store.dispatch('loadUser')
    },


When I try to get the username in the top menu component, it is undefined (as I understand it, because we have not had time to get the data from the server yet), and if I do a v-if check, nothing will be displayed.
computed: {
        username() {
            return this.$store.getters.username
        }
    }


How to implement it correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2020-10-21
@betterthanyouthink

and if I do a v-if check, then nothing will be displayed.

from what fright? As soon as the data arrives, it will be displayed immediately. If is a good option.
You can also attach a global loader (in the sense of animation, a spinner on top of the page) and spin it until the primary data is loaded.
Or hang skeletons (this is such a gray flickering plate that imitates content) in the right places. Also on if-else.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question