how can i load axios calls before page loads



  • Hello please i do need help. When a user has been authenticated and token is stored in session as soon as the page loads it re-authenticates the token. At that process my state is turned to null and after token is verified after few seconds is there anyway to make the calls and return response before the pages load and render the user the authenticated page (Dashboard, Signout) rather than having (Signin and signout)

    When the page loads it show
    alt text

    while confirming from the backend after some seconds it shows below

    alt text

    is there a way to sort the issues before the page loads. because it means that if my page loads it would remain like this for a while

    alt text

    causing issues

    Any assistance is welcomed

    my custom-main.js in my boot file

    import Vue from 'vue'
    import axios from 'axios'
    
    // require('./store/subscriber')
    export default async ({ app, router, store, Vue }) => {
      	axios.defaults.baseURL= 'http://127.0.0.1:8000/api'
    
    	store.dispatch('auth/attempt', localStorage.getItem('token'))
    }
    

    My store/index.js

    import Vue from 'vue'
    
    import Vuex from 'vuex'
    
    Vue.use(Vuex)
    
    
    import state from './state'
    import *  as getters from './getters'
    import *  as mutations from './mutations'
    import *  as actions from './actions'
    
    import auth from './modules/auth/auth'
    import shopping from './modules/shopping'
    
    export default new Vuex.Store({
    	state,
    	getters,
    	mutations,
    	actions,
    	modules:{
    		auth,
    		shopping
    	}
    })
    
    
    require('./modules/auth/subscriber.js')
    

    my subscriber.js to check if a token is in the local storage to change the mutation at the page load

    import store from 'app/src/store/index'
    import axios from 'axios'
    
    store.subscribe((mutation)=>{
    	// console.log(mutation)
    	switch (mutation.type){
    		case 'auth/SET_TOKEN': 
    		console.log(mutation.payload)
    		if (mutation.payload){
    			console.log(localStorage.getItem('token'))
    			axios.defaults.headers.common['Authorization'] = `Bearer ${mutation.payload}`
    			localStorage.setItem('token', mutation.payload)
    		}else{
    			axios.defaults.headers.common['Authorization'] = null
    		}
    		break;
    	}
    })
    

    my vux auth.js

    import axios from 'axios'
    
    export default ({
    	namespaced: true,
    
    	state: {
    		token: null,
    		user: null,
    		phone: null,
    	},
    
    	getters:{
    		authenticated (state){
    			return state.token && state.user
    		},
    
    		user(state){
    			return state.user
    		},
    
    		phone(state){
    			return state.phone
    		}
    	},
    
    	mutations: {
    		SET_TOKEN (state, token) {
    			state.token = token
    		},
    
    		SET_USER (state, data) {
    			state.user = data
    		},
    
    		SET_PHONE_NUMBER (state, phone) {
    			state.phone = phone
    		}
    	},
    
    	actions: {
    		async signIn({dispatch}, credentials){
    			let response = await axios.post('auth/signin', credentials);
    			// console.log(response.data)
    			return dispatch('attempt', response.data.token)
    		},
    
    		async attempt({ commit, state }, token){
    			// console.log(token)
    
    			if(token){
    				commit('SET_TOKEN', token)
    
    			}else{
    				console.log('bad')
    			}
    
    
    			if(!state.token){
    				return
    			}
    
    			try{
    				let response = await axios.get('auth/me')
    
    				// set headers in subsribers.js
    				
    				// console.log(state.token)
    
    				commit('SET_USER', response.data)
    
    			}catch (e){
    				// console.log('failed')
    				commit('SET_USER', null)
    				commit('SET_TOKEN', null)
    			}
    		},
    		
    		signOut({ commit }){
    			return axios.post('auth/signout').then(() =>{
    				commit('SET_USER', null)
    				commit('SET_TOKEN', null)
    			})
    		},
    
    		async sendPhoneNumber({commit, dispatch}, phone_number){
    			return new Promise((resolve, reject) => {
    	            axios.post('phone', phone_number).then(response => {
    	                dispatch('flashMessage', response.data.data.message, {root:true})
    	                resolve(response);
    					commit('SET_PHONE_NUMBER', phone_number)
    	            }, error => {
    	                dispatch('flashErrorMessage', error.response.data, {root:true})
    	                // console.log(error.response.data.data.error)
    	                reject(error.response.data.data.error);
    	            })
    	        })
    		},
    
    		async verifyOTP({commit, dispatch}, credentials){
    			return new Promise((resolve, reject) => {
    	            axios.post('verify-otp', credentials).then(response => {
    	                dispatch('flashMessage', response.data.data.message, {root:true})
    	                resolve(response);
    	            }, error => {
    	                dispatch('flashErrorMessage', error.response.data, {root:true})
    	                console.log(error.response.data.data)
    	                reject(error.response.data.data);
    	            })
    	        })
    		},
    
    		async signUp({dispatch}, credentials){
    			let response = await axios.post('auth/signup', credentials);
    			console.log(response.data)
    			console.log(response.data.data.message)
    			return dispatch('attempt', response.data.data.message.token)
    		},
    	},
    })
    
    

    and my component file

    <template>
        <q-layout view="hHh Lpr lFf">
            <q-header elevated style="background-color:white; height:100px;">
                <q-toolbar class="q-pl-xl text-primary">
                    <q-toolbar-title>
                        <img src="statics/parkit_logo.jpeg" alt="Parkit Home service" width="110">
                    </q-toolbar-title>
                    <!-- <q-space /> -->
                    <template v-if="authenticated">
                        <q-btn flat color="primary" label="Dashboard" />
                        <q-btn flat color="primary" label="Logout" />
                    </template>
                    <template v-else>
                        <q-btn flat color="primary" label="Sign In" @click="signInModal = true" />
                        <q-btn flat color="primary" label="Sign Up" @click="signUpModal = true" />
                    </template>
    
    
                    <div class="q-pa-md" v-if="cart.length">
                        <q-btn-dropdown color="primary" :label="carTotalLength" v-model="menu" @mouseover.native="menuOver = true" @mouseout.native="menuOver = false">
                            <div class="q-pa-sm">
                                <b>YOUR CART ITEM</b>
                            </div>
                            <hr>
                            <q-list @mouseover.native="listOver = true" @mouseout.native="listOver = false" >
                                <q-item v-for="item in cart" :key="item.id">
                                    <q-item-section>
                                        <q-item-label>
                                            {{item.quantity}}  x  <b>{{item.product.package}}</b> -  {{item.product.vehicle}} @ ₦ 
                                            {{item.product.amount}} 
                                            <q-card-actions align="right">
                                                <q-btn flat @click.prevent="removeProductFromCart(item.product.id)">Remove</q-btn>
                                            </q-card-actions>
                                        </q-item-label>
                                    </q-item-section>
                                </q-item>
                                <q-card-actions align="around">
                                    <q-btn flat @click.prevent="removeAllProductFromCart()">Clear Cart</q-btn>
                                    <q-btn flat>Checkout</q-btn>
                                </q-card-actions>
                            </q-list>
                        </q-btn-dropdown>
                    </div>
                    <q-btn
                        flat
                        dense
                        round
                        @click="leftDrawerOpen = !leftDrawerOpen"
                        icon="menu"
                        aria-label="Menu"
                        class="lt-sm"
                        />
                </q-toolbar>
            </q-header>
            <q-drawer
                v-model="leftDrawerOpen"
                show-if-above
                bordered
                content-class="bg-grey-2"
                class="lt-sm"
                >
                <q-list>
                    <q-item-label header>Essential Links</q-item-label>
                    <hr>
                    <q-item clickable tag="a" target="_blank" href="https://quasar.dev">
                        <q-item-section avatar>
                            <q-icon name="school" />
                        </q-item-section>
                        <q-item-section>
                            <q-item-label>One</q-item-label>
                            <q-item-label caption>quasar.dev</q-item-label>
                        </q-item-section>
                    </q-item>
                    <q-item clickable tag="a" target="_blank" href="https://github.quasar.dev">
                        <q-item-section avatar>
                            <q-icon name="code" />
                        </q-item-section>
                        <q-item-section>
                            <q-item-label>Two</q-item-label>
                            <q-item-label caption>github.com/quasarframework</q-item-label>
                        </q-item-section>
                    </q-item>
                    <q-item clickable tag="a" target="_blank" href="https://chat.quasar.dev">
                        <q-item-section avatar>
                            <q-icon name="chat" />
                        </q-item-section>
                        <q-item-section>
                            <q-item-label>Three</q-item-label>
                            <q-item-label caption>chat.quasar.dev</q-item-label>
                        </q-item-section>
                    </q-item>
                </q-list>
            </q-drawer>
            <q-page class="page-con">
                <router-view />
            </q-page>
        
            <q-dialog v-model="signInModal">
                <SignIn/>
            </q-dialog>
    
            <q-dialog v-model="signUpModal">
                <SignUp/>
            </q-dialog>
    
            <Footer/>
        </q-layout>
    </template>
    <style scoped>
        .header-box{
        position: absolute;
        top: 0;
        }
        .custom-caption{
        text-align: left;
        padding: 12px;
        color: white;
        background-color: rgba(0, 0, 0, .5);
        height: -webkit-fill-available;
        padding: 220px 80px 75px;
        }
    </style>
    <script>
        import Footer from 'components/Website/Footer.vue'
        import SignUp from 'components/Website/SignUp.vue'
        import SignIn from 'components/Website/SignIn.vue'
        import { mapActions, mapGetters } from 'vuex'
    
        export default {
            name: 'MyLayout',
    
            components:{
                Footer,
                SignUp,
                SignIn
            },
            
            data () {
                return {
                    leftDrawerOpen: false,
                    menu: false,
                    menuOver: false,
                    listOver: false,
                    signInModal: false,
                    signUpModal: false,
                }
            },
            computed: {
                ...mapGetters({
                    cart: 'shopping/cart',
                    cartItemCount: 'shopping/cartItemCount',
                    cartTotal: 'shopping/cartTotal',
                    authenticated: 'auth/authenticated',
                }),
                
                carTotalLength(){
                    return "Cart (" + this.cartItemCount + ") - ₦" + this.cartTotal
                }
            },
    
            mounted(){
                this.authenticated
            },
    
    
            methods:{
                ...mapActions({
                  removeProductFromCart: 'shopping/removeProductFromCart',
                  removeAllProductFromCart: 'shopping/removeAllProductFromCart',
                }),
            }
        }
    </script>
    


  • @schneidershades use a v-if with a data flag set from false to true when your api call resolves. Your api call is obviously async so you need to keep that in mind.


Log in to reply