1

I have a small Laravel / VueJS app with single file components and it is a single page application. I use vue-stash for central state managment.

Here is my store.js

export default {
    user: {
        name: null
    }
}

And here is my api call from my dashboard.

<script>
    export default {
        mounted() {
            axios.get('/api/getAuthUser')
                    .then(response => {
                        this.$store.user.name = response.data.name;
                    });
        }
    }
</script>

This works fine and it will set the user name in store to the user name i get from my api call.

But if the first visit to my site is not the dashboard then there is no api call and the name is not set in the store. But I need that name at different places in my app.

I don't wont to call my api from every component. Is it possible to call the api only once directly from my store? How can I do that or is there any better solution?

Thanks!

// UPDATE

Is there any way to make a direct call from the store.js?

export default {
user: {
    name: null
},
ready () {
    axios.get('/api/getAuthUser')
        .then(response => {
            this.user.name = response.data.name;
        });
    }
}

This does not work. name is still null

// Update 2

import axios from 'axios'

axios.defaults.headers.common = {
    'X-CSRF-TOKEN': Laravel.csrfToken,
    'X-Requested-With': 'XMLHttpRequest'
};



export default {
    user: {
        name: null
    },
    setUser() {
        axios.get('/api/getAuthUser')
        .then(response => {
        this.user.name = response.data.name;
    });
}}

This is my complete store.js but it seems that setUser() does not get executed.

3
  • Do you have root component?
    – dfsq
    Mar 10, 2017 at 12:21
  • Well you should make API call in your root component and pass it down to other component.Or make API call into the store itself and then import store where it's needed and display data that you need. Mar 10, 2017 at 12:25
  • How can i make a api call directly from my store? See my update Mar 11, 2017 at 7:49
0

If you need your user on every page, what about something like this?

new Vue({
   el: "#app",
   mounted: function() {
     // make a request to the api here
   },
});
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.