Having trouble with [Object Object] errors in your hybrid app using Javascript?

I'm currently developing a hybrid app using Nuxt JS, Cordova, and Cordova Native Storage (essentially localstorage).

During the process of saving an object to native storage and retrieving it on page load within the mounted() method, I keep encountering a recurring error regardless of my attempts to access the object data:

[Object Object]

The JavaScript code in the component that is loaded on every page is as follows:

import { mapState } from 'vuex';

export default {
  mounted () {
    document.addEventListener("deviceready", this.getNativeStorage(), false)
  },
  methods: {

    getNativeStorage() {
      window.NativeStorage.getItem("beacon_native_storage", (value) => {
        var parseObj = JSON.parse(value)
        alert(parseObj)
        alert(parseObj.localStorage)
      }, (error) => {
        alert(`Error: ${error.code}-${error.exception}`)
      });
    },

    refreshNativeStorage(currentState) {
      window.NativeStorage.initWithSuiteName("beacon");
      window.NativeStorage.setItem("beacon_native_storage", JSON.stringify(currentState), () => {
        alert('Stored currentState')
      }, (error) => {
        alert(`Error: ${error.code}`)
      });
    }

  },
  computed: {
    state () {
      return this.$store.state
    }
  },
  watch: {
    state: {
      handler: function (val, Oldval) {
        setTimeout(function () {
          this.refreshNativeStorage(this.state)
        }.bind(this), 10)
      },
      deep: true
    }
  }
}

Furthermore, the object retrieved from Vuex is structured like this:

export const state = () => ({
  pageTitle: 'App name',
  dataUrls: [],
  intervalData: [],
  settings: [],
  experimentalFeatures: [],
  customAlertSeen: false,
  user: null,
  account: null,
  payloadOutput: null
})

Each time the getItem function runs, the alert(parseObj) always displays [Object Object] instead of the actual data. And when trying to access specific properties such as parseObj.localStorage.pageTitle which are clearly defined in store/localStorage.js, it returns undefined.

I am puzzled by where I might be making mistakes in this implementation. Any guidance would be greatly appreciated.

Answer №1

Here's the deal with localStorage: it actually stores data as strings, not as objects.

So when you want to save something to localStorage, be sure to stringify it first, and then parse it back into an object when you retrieve it.

localStorage.setItem('key', {property:'value',anotherProperty:'anotherValue'})

localStorage.getItem('key')  // "[object Object]" <- keep in mind the quotes!

localStorage.setItem('key', JSON.stringify({property:'value',anotherProperty:'anotherValue'}))

JSON.parse(localStorage.getItem('key')) // {property: "value", anotherProperty: "anotherValue"}

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

What is the mechanism behind lazy module loading in typescript?

Exploring the concept of lazy loading in typescript, the author provides an example in this section of their book. They demonstrate it using the following piece of code: import bar = require('bar'); export function loadBar() { ...

What is the quickest method for retrieving li data using selenium?

Greetings! Your attention to this post is greatly appreciated. I recently set out to gather insights on a particular news article. Out of the staggering 11,000 comments attached to the news piece, I was able to acquire data from approximately 6,000 commen ...

Error in the Syntax of Project Image Slider

I'm encountering an issue with a WordPress script called Project Slides. Initially, this script was working fine but suddenly stopped. After investigating in the console, I found the following error: VM138 plupload-image.js?ver=4.2.2:67 Uncaught Err ...

The Redux UI does not refresh when altering the state of a nested array

As someone who is relatively new to Redux, I am facing an issue with my web application which is an eCommerce platform. In this application, users can create multiple carts, each with a unique id and name, and add different items to these carts stored in a ...

The 'api' property is not found within the 'MyService' type declaration

Currently, I am working on a tutorial where we are building an Angular service to send emails from a form using the Mailthis Email API. In the code for the service, I encountered an error related to the 'api' variable that states "Property ' ...

Toggle the element within the selected row using Jquery

In order to create a client list, users must click on rows to select them and then submit the selections to the database for a cron job to send out emails. Instead of using checkboxes, I am attempting to highlight rows by including two hidden elements - o ...

An error was encountered in customizing CKEditor5 in Vue: compilation unsuccessful

I tried to integrate a custom CKEditor5 into my Vue application, but encountered a failed to compile error. I generated the custom build using the online tool provided by CKEditor. Subsequently, I placed the files in a new folder called ckeditor within th ...

The proper method for utilizing the clipped prop on the <v-navigation-bar/> component within Vuetify is as follows

Looking for the correct way to apply the clipped prop to <v-navigation-draw/> in a Vuetify application in order to ensure that the navigation drawer sits below the app-bar. Here is what I have tried so far. Started with a new project: $ vue create ...

Encountering an error when attempting to save an ajax JSON response to a variable and receiving an

I am attempting to make an ajax call and store the JSON response in a variable. My goal is to display the JSON response in two separate Jqgrids, with one displaying half of the response and the other displaying the remaining half. I need some ideas on how ...

Tips for setting background colors as a prop for Material UI cards in React JS

Currently utilizing the Material UI next framework to construct a wrapper for the card component. This customized wrapper allows for personalization of the component. I have successfully extended the component so that the title and image within the card ca ...

Image transformed by hovering effect

I've been attempting to add a hover effect to the images in my WordPress theme. The images are displayed in a grid format, created by the featured image on the posts. The grid layout is controlled within content.php <?php /** * controls main gri ...

"Excessive use of Javascript setInterval combined with frequent ajax calls is causing significant

I have integrated the setInterval() function into my JavaScript code to make an AJAX call every 2 minutes. However, I noticed that this is causing the website to slow down over time. The website is built using Node.js. After doing some research, I came acr ...

Access to the Heroku app is restricted to the specific device that I have designated for its

I am having some issues with deploying my app and need some help. Here are the details: Using the free plan on Heroku On other devices, only the background image/color/pattern is visible Errors on other devices (mainly related to Redux): On Firefox ...

The browser does not automatically set the Cookie

Trying to login involves making an API call using a POST HTTP request. post( postLogin(email), JSON.stringify({password: passwd}), { headers: { "Content-Type":"application/json" }, credentials: 'include' // also attempted with &a ...

Combining CSS, jQuery, and HTML into a single .html file would allow for seamless integration

I've been searching extensively, but I haven't been able to locate exactly what I need. My goal is to merge my jQuery and CSS into a single .html file, but I'm struggling to get the jQuery functionality to work. Although I have experience wi ...

Encountered issue while initializing object from controller in AngularJS

Here is the demonstration on how the fiddle appears: var app = angular.module('testApp', []); app.controller = angular.('testAppCtrl', function ($scope) { $scope.vehicle = { type: 'car', color: 're ...

Incorporating the id attribute into the FormControl element or its parent in Angular 7

I'm attempting to assign an id attribute to the first invalid form control upon form submission using Angular reactive forms. Here is my current component code: onSubmit() { if (this.form.invalid) { this.scrollToError(); } else { ...

Concealing applicationId and clientToken in Datadog

I'm currently using an Angular application and I've integrated it with the Datadog application to utilize Session and Replay (RUM). However, I am concerned about the security of my sensitive information such as applicationId and clientToken. Is t ...

Resize an image to fit perfectly within a material-ui grid

Is there a way to resize images within a grid layout without them getting cropped? Each image I try to fit into the top horizontal grid behaves differently due to varying dimensions. Instead of stretching and fitting into the container, the images end up b ...

What is the process of attaching classes in vuejs?

I am attempting to bind multiple classes using v-bind:class for radio buttons that I want to apply Bootstrap classes to when they are active. However, it seems like I am not adding the classes correctly. <div id="app"> <div class="btn-gr ...