0

I have a class:

export class CartItem {  
  productname!: string;
  quantity!: number;
}

I store an array of this in session as:

cartItems: Array<CartItem> = [];
...
...
sessionStorage.setItem("CurrentCart", JSON.stringify(this.cartItems));

When retrieving this, I tried:

this.cartItems = JSON.parse(sessionStorage.getItem("CurrentCart") || '') as Array<CartItem>;

But this returns:

Cart Items [object Object],[object Object],[object Object],[object Object]

and not the array with values.

From what I see in some examples Angular convert json to array of object, seems I need to map the array back or write a custom transformer https://medium.com/typescript-center/casting-json-objects-to-typescript-classes-a-deep-dive-835b8f8988bf

Is that the only way? Seems inefficient and cumbersome for bigger classes.

3
  • That should not happen and I sincerely doubt it actually happens. However, without a fully working example, it is hard to tell what and where things are going wrong. Please provide a working example demonstrating the problem. Commented Mar 4, 2024 at 13:48
  • The round trip to JSON just gives you vanilla objects, you can't serialise classes to JSON. So yes if you want to rehydrate class instances you have to have code to do that. Commented Mar 4, 2024 at 13:52
  • Is there a more efficient way to store and retrieve data in a session without having to parse every single time? We allow users to navigate all over the app and have cart visible Commented Mar 4, 2024 at 18:50

1 Answer 1

1

JSON.parse will not convert some arbitrary json to the CartItem class. It will simply convert a json string to json primitives (string, boolean, null, array, object).

You would need to implement some custom encoding/decoding. Example:

class CartItem {
  constructor(public productName: string, public quantity: number){}
  toJson(): any {
    return {productName: this.productName, quantity: this.quantity}
  }
  toString(): string{
    return `CartItem{${this.productName}:${this.quantity}}`
  }
  static fromJson(obj: any): CartItem {
    return new CartItem(obj.productName, obj.quantity)
  }
  static fromJsonList(obj: any): CartItem[] {
    return obj.map(item => CartItem.fromJson(item))
  }
}

class Cart {
  private cartItems: CartItem[] = []
  private static readonly STORE_KEY = "CurrentCart"
  function save(){
    const storedJson = JSON.stringify(this.cartItems.map(item => item.toJson()))
    sessionStorage.setItem(Cart.STORE_KEY, storedJson);
  }
  function load(){
    const storedJson = sessionStorage.getItem(Cart.STORE_KEY) || '[]'
    this.cartItems = CartItem.fromJsonList(JSON.parse(storedJson));
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a more efficient way to store and retrieve data in a session without having to parse every single time? We allow users to navigate all over the app and have cart visible.
@BlahFoo I wouldn't worry about that. The performance hit should be negligible, unless you're doing it hundreds of times a second.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.