Home  >  Q&A  >  body text

How to return an observer from a global function in Vue 2

<p>Hello, I have a question: In main.js, I have a global function <code>getSites</code> that retrieves the list of sites from the API. </p><p> This function works using async/await and returns site data asynchronously. </p><p> I also have a global variable called <code>lockSitesLoading</code> which I set to true when I start getting data from the API, I need this variable to prevent the client from making new requests to the server. </p><p> In the first function <code>getSites</code>, I need to check this variable <code>lockSitesLoading</code> and if it is true, start monitoring it until it changes to false. At this point, I want to call <code>getSites</code> recursively. </p><p> The problem starts now because when I start watching the variable, the function does not wait for the variable to become false, but returns <code>undefined</code>. </p><p> Here is my code: </p> <p>Component.vue:</p> <pre class="brush:php;toolbar:false;">async mounted() { let vm = this; const sites = await vm.getSites(); vm.sites = sites.data },</pre> <p>main.js:</p> <pre class="brush:php;toolbar:false;">async getSites() { let vm = this; if (vm.$store.state.lockSitesLoading) { vm.$watch('$store.state.lockSitesLoading', () => vm.getSites()); } else { return vm._getSitesOnline(); //This is the function that actually gets the data from the server }</pre> <p>I tried solving it this way but it doesn't work. Any ideas? </p>
P粉682987577P粉682987577409 days ago467

reply all(2)I'll reply

  • P粉788571316

    P粉7885713162023-09-06 19:21:54

    I don’t know if you set lockSitesLoading = true, and I don’t know where you set it.

    This is a working example.

    Vue.use(Vuex)
    
    const store = new Vuex.Store({
      state: {
        sites: [],
        lockSitesLoading: false
      },
      actions: {
        async loadSites(context) {
            context.state.lockSitesLoading = true;    
            const sites = await context.dispatch('getSites');
            context.state.sites = sites.data;
            context.state.lockSitesLoading = false;    
        },
        async getSites(context) {
            return new Promise(function(resolve, reject){
              setTimeout(function(){
                resolve({ data: ['site1', 'site2', 'site3']})              
              },1000)
            })
          }    
      }
    })
    
    new Vue(
      { 
        el:'#app',
        store: store,
        async mounted() {
           await this.$store.dispatch('loadSites')
        },
        computed: {
          sites() { return this.$store.state.sites },
          lockSitesLoading() { return this.$store.state.lockSitesLoading }
        },
        watch: {
          lockSitesLoading(newVal, oldVal) {
              console.log(`lockSitesLoading: ${oldVal} -> ${newVal}`)
          }
        }    
      }
    )
    #app { line-height: 1.75; }
    [v-cloak] { display: none; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.7.14/vue.min.js"></script>
    <script src="https://unpkg.com/vuex@3.6.2/dist/vuex.js"></script>
    <div id="app" v-cloak>
      sites: {{sites}}<br/>
      lockSitesLoading: {{lockSitesLoading}}
    </div>

    reply
    0
  • P粉063039990

    P粉0630399902023-09-06 09:50:26

    Basically requires a promise to wait for:

    let unwatch;
    
      await new Promise(resolve => {
        unwatch = vm.$watch('$store.state.lockSitesLoading', loading => {
          if (!loading) {
            resolve();
          }
        }, { immediate: true });
      });
    
      unwatch();
    
      await vm._getSitesOnline();

    Please note that if lockSitesLoading blocks execution for some reason, this will cause a memory leak.

    There may be a cleaner way to achieve this using the composition API and VueUse compositions.

    reply
    0
  • Cancelreply