Background Sync with Workbox in Vue

2.3k views Asked by At

I am trying to make a background-sync request with WorkBox, in a very simple example application with Vue. I revised my codes for a long time but I did not find the solution, or maybe, something is wrong in my code.

The service worker is well registered and when I make the ajax request, background-sync is activated.

VUE

<template>
  <div class="users">
    <h1>USERS</h1>
    <input type="text" v-model="qty" placeholder="How many users to find">
    <button @click.prevent="search()">How many users would you like to find?</button>
    <ul>
      <li v-for="user in users">
        {{user.email}}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data(){
    return {
      users: null,
      qty: 10
    }
  },
  methods:{
    search(){
      axios.get('https://randomuser.me/api', {
        params: {
          results: this.qty
        }
      })
      .then(response => {
        console.log(response);
        this.users = response.data.results
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

VUE.CONFIG.JS

module.exports = {
  // ...other vue-cli plugin options...
  pwa: {
    name: 'My App',
    themeColor: '#4DBA87',
    msTileColor: '#000000',
    appleMobileWebAppCapable: 'yes',
    appleMobileWebAppStatusBarStyle: 'black',

    workboxPluginMode: 'GenerateSW',
    workboxOptions: {
      runtimeCaching: [{
        urlPattern: new RegExp('https://randomuser.me/api'),
        handler: 'networkOnly',
        options: {
          //background sync. conf
          backgroundSync: {
            name: 'my-queue-asier',
            options: {
              maxRetentionTime: 60 * 60,
            }
          }
        }
      }]
    }
  }
}

These are screenshots from the DevTools when the events are fired.

When the network is disconnected I receive this errors in the console. I am not sure if is it normal if background sync works well...

background-sync is registered in indexDB tab

Finally the network tab. There we see that the API call is well, because when the network returns it makes the call, but nothing else happens in the app, and the old data is not replaced by the new one :/

Can anybody help me? I look for that but I didnĀ“t find anything...

Thanks!

1

There are 1 answers

7
Aashish Singla On

If you have a GET call to cache, as your code snippet suggests, then you do not need a background sync. You just need a construct of runtimecaching with the right handler and url pattern to get GET calls cached. You shall need background sync for POST/PUT/DELETE calls.