Ways to confirm the existence of local storage in Vue.js data

Recently, I created a to-do list using Vue js and localstorage(LS). Everything was working fine until I tried to run it on a different browser where LS is not allowed. An error popped up saying

Cannot read property 'items' of null"
. The issue seems to be that I need to verify LS before utilizing it, but unfortunately, I am accessing LS in Data where checking it is not possible.

Below is an excerpt of my code:

var app = new Vue({
el: '.row',
data:{
    cap:undefined,
    ti:undefined,

    forLS:{
        items:[]
    },
    count:-1,
    forLS:JSON.parse(localStorage.getItem("allData")),
    count:JSON.parse(localStorage.getItem("count"))
    }

I attempted to access LS within a function, but it seems impossible to execute it in Data. You can view the entire code HERE. I am struggling to find a solution to this problem. Thank you for any help in advance!

Answer №1

You should consider implementing a fallback plan in case the localStorage turns out to be empty:

{
    el: '.row',
    data:{
        cap:undefined,
        ti:undefined,
        forLS:JSON.parse(localStorage.getItem("allData") || '{ "items":[] }'),
        count:JSON.parse(localStorage.getItem("count") || '-1' )
}

Here is a modified version with a working solution based on your code

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Need a place to keep your data safe while using nodejs?

I have taken on the task of developing a lastfm plugin for a chat bot that my friend created. One feature I want to include is the ability for users to register their hostmask/nick with their lastfm username (for example, using the command !reg lastfmuser ...

Obtaining JSON information with Svelte

I'm currently facing a mental block. My goal is to fetch JSON data using the Youtube API. The error message I am encountering is "Cannot read property 'getJSON' of undefined". Here's the code snippet I have provided: <script> ...

Acquiring JSON-formatted data through the oracledb npm package in conjunction with Node.js

I am currently working with oracledb npm to request data in JSON format and here is the select block example I am using: const block = 'BEGIN ' + ':response := PK.getData(:param);' + 'END;'; The block is ...

Updating the state of a different Vue component

I am in need of updating the isHidden value to true within my code split into different components: // Profile.vue <UserData v-bind:user_billing="user_billing" v-bind:user_profile="user_profile" ></UserData> <div class="col-12 px- ...

Developing various VueJS TypeScript projects utilizing a shared library

In the process of developing two VueJS applications using TypeScript, I have created one for public use and another as an admin tool exclusively for my own use. Both applications are being built and tested using vue-cli with a simple npm run serve command. ...

utilize vuejs to display an alternative route on a side panel

As I develop a back office using Quasar, I am exploring the possibility of creating what I would call a sidepage to open routes. This sidepage would display the requested component without any additional decoration, such as menus. However, there is also a ...

Is selectpicker acting up?

Currently, I am troubleshooting a filter feature on a website that utilizes jQuery with JSON data. Everything was functioning properly until recently when an error started appearing: The selectpicker function is not recognized I would greatly appreciat ...

Utilize Laravel's accessor in Vue for seamless data retrieval

I've encountered an issue with one of my Laravel 5.4 models that has multiple accessors implemented like shown below: public function getRevenueAttribute() { return $this->calculate()->revenue($this->price, $this->amount); } The prob ...

What strategies can be used to ensure that the page layout adjusts seamlessly to even the smallest shifts in window size?

Of course, I am familiar with media queries and how they allow us to set specific min-width and max-width ranges for CSS changes. However, when I look at the website styledotme.com, I notice that the block/div beneath the navigation bar gradually shrinks ...

Error: 'POST Request Processing Failure: Content-Type Missing'

My front end Canvas is transformed into a png file that needs to be POSTed to a third party vendor's API. The response comes back to Node as a base64 file which I decode, but upon attempting the upload, an error occurs: Error processing POST reques ...

Display the username on a Meteor React component

I'm facing an issue with one of my React components, which serves as the main layout for my application. It includes a navigation bar that displays the username of the currently logged-in user. The problem arises when Meteor.user() returns undefined d ...

Methods for organizing consecutive elements within an array in Javascript/Typescript

Let's explore this collection of objects: [ { key1: "AAA", key2: "BBB" }, { key1: "BBB", key2: "CCC" }, { key1: "CCC", key2: "DD ...

Name the Angular interpolation function with the (click) event

I have a JSON file that defines different dynamic buttons, but when I click on them, the function is not being called. Here's how my JSON file looks: export const liveButtonData = [ { title: 'My Name', function: 'getName()'} ...

At that specific moment, a plugin is active to monitor the execution of JavaScript functions

Similar to how Fiddler allows you to monitor the communication between client and server, I am looking for a tool that can analyze all network traffic generated by client-side JavaScript on a webpage. Warm regards, bd ...

Alter the Vue view using an object instead of the url router

Currently working on a chrome extension using Vue.js where I need to dynamically update views based on user interactions. Usually, I would rely on the Vue Router to handle this seamlessly... however, the router is tied to the URL which poses limitations. ...

Creating a progress bar with blank spaces using HTML, CSS, and JavaScript

Upon running the code below, we encounter an issue when the animation starts. The desired effect is to color the first ten percent of the element, then continue coloring incrementally until reaching 80%. However, as it stands now, the animation appears mes ...

Rearrange the provided string in a particular manner

Looking to transform a string like '12:13:45.123 UTC Sun Oct 17 2021' into 'Sun Oct 17 2021 12:13:45.123 UTC' without calling slice twice. Is there a more elegant and efficient way to achieve this? Currently using: str.slice(18)+&apo ...

"Encountering an error while attempting to map a JSON array in

I am just starting to work with knockoutjs and I'm attempting to map JSON data to KO. Here is my code: My goal is to parse the JSON data and display it in a table. However, when I try to use ko.compute, I encounter an error saying "self.firstName() i ...

Executing Firebase Cloud Functions to perform write operations within a database event function

Exploring the world of Firebase functions has been an exciting learning journey for me. This innovative feature is proving to be incredibly powerful and beneficial. I'm eager to utilize a function that can capture a database writing event, perform a ...

Encountered an issue with the Mongoose Schema method: The model method is not recognized as a

Here are two Mongoose model schemas that I am working with. The LabReport model includes an array that references the SoilLab model. Within the SoilLab model, there is a static method that was initially used to choose which fields to display when retrievin ...