Error message "The result of this line of code is [object Object] when

Recently, I encountered an issue while retrieving an object named userInfo from localStorage in my Angular application. Despite successfully storing the data with localStorage.setItem(), I faced a problem when attempting to retrieve it using localStorage.getItem. Instead of receiving the complete object, all I got was [object Object].

In my productService.ts file:

  public setUserInfoInLocalStorage: any = (data) => {
    localStorage.setItem('userInfo', JSON.stringify(data))
  }

  public getUserInfoFromLocalStorage: any = () =>{
    return JSON.parse(localStorage.getItem('userInfo'))
  }

And in my component.ts file:

this.productService.setUserInfoInLocalStorage(apiResponse.data.userDetails);
console.log(this.productService.getUserInfoFromLocalStorage()); //Instead of JSON, [object Object]

This is the complete data I received after login:

{"error":false,"message":"Login Successful","status":200,"data":{"authToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...(text truncated for brevity)

And this is how the data looks after saving in local storage:

userInfo:"{"userId":"9Cgs6iExE","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="592d3c2a2d68192d3c2a2d68773a3634">[email protected]</a>","isSeller":true}" 

Answer №1

In the event that localStorage.getItem('key') is returning [object Object] instead of a String:

  1. Simply remove it by using localStorage.removeItem('key').
  2. Prior to executing
    localStorage.setItem('key', value)
    , make sure to check the type of value to determine whether it is a String or an Object. This issue can be avoided if value is strictly a String.

You have the option to verify the variable type by utilizing console.log(typeof value);

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 best way to hand off a component to a helper function?

I am trying to create a helper function in TypeScript that takes a component as an argument and returns an array of objects, each containing a component node... // helpers.ts import { LINKS } from '../constants'; // error on the next line: Cannot ...

Problem with jasmine unit testing in a firebase-integrated ionic/angular application

I am currently working on an app using the Ionic and Firebase frameworks, and I have encountered an issue while writing unit tests for it. The error message I received is: Cannot read property 'subscribe' of undefined This error occurs during t ...

Angular 2's ngModel feature allows for easy data binding and manipulation, particularly

I currently have an array of objects structured like this... this.survey = [ {id: 1, answer: ""}, {id: 2, answer: ""}, {id: 3, answer: ""}, {id: 4, answer: ""}, {id: 5, answer: ""}, {id: 6, answer: ""}, {id: 7, a ...

Add navigation dots to the slider in order to align them with the specified div element

Visit this JSFiddle link for the code <html> <link href="./style.css" rel="stylesheet" type="text/css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script&g ...

Unpacking intricate function arguments in TypeScript

I am working with the following model classes: export class Book { public name: string; public id: string; ... } export class Author { public firstName: string; public lastName: string; ... } The my-component triggers an event t ...

Creating dynamic object rotation based on a new pivot point using Three.js

In Three.JS, I've successfully created a spiral with downward movement. However, I am struggling to implement the knocking motion. https://i.sstatic.net/VrykN.gif var planeGeometry = new THREE.PlaneGeometry(10,10); var planeMaterial = new THREE.Mesh ...

I am currently facing a challenge in animating my ng-show/ng-hide animation

This particular issue has been widely recognized and discussed multiple times in various forums. Despite the extensive search, I have not come across satisfactory solutions. var aniApp = angular.module("aniApp", []); aniApp.controller('mainCtrl&ap ...

"Could you please provide me with further details on how to use sequelize

I recently started working with node js and I used sequelize-auto to generate the models. However, I encountered an error when following the guidance provided in this link https://github.com/sequelize/sequelize-auto. If you need further clarification on th ...

Leveraging angular.extend() with controllers and function overrides

Currently, I am working with Angular 1.4.8 and attempting to expand a controller. The original controller and the expanding controller are quite similar, but there is a specific function that I aim to replace in the extending controller. angular.module(&a ...

What could be causing the error message to appear in Angular CLI when attempting to add a new component?

I recently started working on a new Angular app and I'm attempting to add a component for a login registration feature. This will be my first time building an app with Angular frontend and Bootstrap backend, as I am fairly new to development. Any advi ...

When using the `create-react-app` command with the `--typescript` flag, you may encounter an issue when attempting to compile namespaces with the `--

I started a project using npx create-react-app my-app-ts --typescript, then I added two new files, sw-build.js and sw.js in the src/ directory. The content of these files was taken from the discussion on Workbox guidelines at (Guidlines for Using Workbox) ...

Incorporate Moment library for date selection in AngularDateRangePicker

I have attempted to implement AngularDateRangePicker according to the instructions provided at the following URL: https://www.npmjs.com/package/ngx-daterangepicker-material However, when I include the line selected: {startDate: Moment, endDate: Moment}; ...

Customizing the styling of buttons in Highcharts is disabled when in full screen mode

I've integrated highcharts into my Angular application and included a custom button inside the chart to navigate users to another page. However, I encountered an issue when trying to fullscreen the chart using the export menu. The position of the cus ...

Restrict HTML Content in Json Result using PHP and Jquery

I'm currently working with a Controller that outputs JSON response and a JavaScript function that appends that response to the last tr in an HTML table. <pre> $reponse="<tr class=\"border_bottom\"><td>My Repo ...

What is the best way to calculate the duration of a .wav file stored locally using JavaScript?

Can you help me figure out how to determine the duration (in milliseconds) of a .wav file using JavaScript for a GreaseMonkey Script? The main challenges I'm encountering are: 1) Accessing local files 2) Retrieving the length of the wav file ...

What is the best way to retrieve an element made in a different function within JavaScript?

I have a main button on the screen and when I click that button, it generates two more buttons. These additional buttons should each have their own functionality and click events, but since they are created within a function without global variables or ids ...

Exploring the integration of Styled-components in NextJs13 for server-side rendering

ERROR MESSAGE: The server encountered an error. The specific error message is: TypeError: createContext only works in Client Components. To resolve this issue, add the "use client" directive at the top of the file. More information can be found here i ...

Creating dynamic components in Vue.js using VueJS and jQuery synergistically

New to Vue.js and in the process of building a Vue component inspired by this custom select menu. I want to include an ionicon with each list item. Typically, I can add the icon in Vue.js using: <component class="icon" :is="name-of-icon& ...

Occasionally, the translate.get function may return the key instead of the intended

I recently encountered an issue while working on a web application built with Angular 12 and ASP.NET Core 5. The application utilizes ngx-translate for internationalization, but I faced a problem with translating content in a new component that I added to ...

AngularJS url update event

In order to gather statistical data, I am interested in tracking how many times the URL has been changed. To achieve this, I have set up a counter that will increment each time the URL is modified. Does anyone have a solution for this? ...