'Get Local Storage Data when internet is online

So I'm trying to get Local Storage data when the internet is online using Vuejs. My ToDo app stack in Vuejs/Laravel/MySQL. Basically, I'm storing data in localStorage when the internet is online. Also, I have added all the functionalities of the ToDo app with offline capabilities like adding, deleting and editing the todo item. I'm unable to post the local storage data to MySQL Database.

updateAllTodos() {
  let data = { todos: this.todos };
  if (navigator.onLine) {
    axios.post(this.api + "/update_all", data).then((res) => {
      localStorage.setItem("todos", JSON.stringify(this.todos));
    });
  } else {
    JSON.parse(localStorage.getItem("todos", JSON.stringify(this.todos)));
  }
},

How can I post the localStorage data when the Internet is Online?



Solution 1:[1]

You can handle this (update onLine status) by using event listener and set the variable true/false. Later you can watch to the data property and do something accordingly.

  data() {
    return {
      isOnLine:navigator.onLine
    }
  },
  mounted() {
     window.addEventListener('online', () => {this.isOnLine = true});
     window.addEventListener('offline', () => {this.isOnLine = false});
  },
  watch: {
   onLine: function (val) {
      if(this.isOnLine){
        // make axios call here
      }
    },
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1