T
T
thehighhomie2019-07-27 13:57:11
Vue.js
thehighhomie, 2019-07-27 13:57:11

How to initialize application when data is loaded via API?

Faced a problem when initializing the application. I'm trying to initialize the application after the data is loaded:
main.js

ApiService.init()

if (JwtService.getToken()) {
  ApiService.setHeader()
  ApiService.mount401Interceptor()
  store
    .dispatch('auth/checkAuth')
    .then(() => {
      store.dispatch('project/getProjectById', router.app.$route.params.projectId)
    })
}

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

app.vue
<template>
  <div
    v-if="isLoaded"
    id="app"
    class="theme-dark"
  >
    <router-view />
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'App',

  computed: {
    ...mapState(['isLoaded'])
  }
}
</script>

store: index.js
import Vue from 'vue'
import Vuex from 'vuex'
import modules from './modules'

Vue.use(Vuex)

export default new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production',

  modules,

  getters: {
    isLoaded (state) {
      return state.auth.user && state.project.project
    }
  }
})

In general, all this works almost normally, but when I write a vuex getter to format project data, and output it somewhere, then errors immediately fly that the project variable does not exist, that is, getters in child components are launched before the data is loaded .
My brain exploded even more when I conditionalized the root component with . The component itself is not created, but the getters work... How to solve this problem? v-if="false"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FullStack Alex, 2019-07-30
@thehighhomie

I don’t quite understand how the first part of main.js works and why v-if="false", but along the way you just need to initialize inside callback then:

ApiService.init()

if (JwtService.getToken()) {
  ApiService.setHeader()
  ApiService.mount401Interceptor()
  store
    .dispatch('auth/checkAuth')
    .then(() => {
      store.dispatch('project/getProjectById', router.app.$route.params.projectId)

      new Vue({
          router,
          store,
          render: h => h(App)
      }).$mount('#app')

    })
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question