Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load an object from server before anything else - vuejs - vuex

So I want to send a request with fetch to get some settings from the server. The response must come before the page loads and I am saving those settings in vuex - so every other component has access to them.

I have been able to send the requst and get the data but whenever I use those vuexed settings in a component they are not there. Here is the vuex:

const state = {
    settings: new Settings,
    is_mobile: MobileCheck(),
}

Here is the settings request:

class Settings {
    constructor() {
        this.endpoint_url = '/api/settings/'
        this.image_file_path = ''
        this.music_sheet_file_path = ''
        this.audio_file_path = ''

        this.get_settings()
    }

    async get_settings () {
        await fetch(this.endpoint_url).then(res => res.json()).then(res => {
            this.image_file_path = res.find(setting => setting.parameter === "image_file_path").value
            this.audio_file_path = res.find(setting => setting.parameter === "audio_file_path").value
            this.music_sheet_file_path = res.find(setting => setting.parameter === "music_sheet_file_path").value
        })
        .catch(err => console.log(err));
    }

    get_image_file_path () {
        console.log(this.image_file_path)
        return this.image_file_path
    }
    get_music_sheet_file_path () {
        return this.music_sheet_file_path
    }
    get_audio_file_path () {
        return this.audio_file_path
    }
}

I am using vue as front and laravel as backend. Maybe I could somehow put the request in the app.js file or maybe you know a better way of doing this. Any help would be great.

like image 429
Vitalii Kyzym Avatar asked Dec 15 '25 04:12

Vitalii Kyzym


1 Answers

As @Naveen mentioned, created() or even beforeCreate() seem like a good choice.

Here is the description from Vue: https://v2.vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks

like image 125
Steve Furches Avatar answered Dec 16 '25 20:12

Steve Furches



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!