0

I've been over this for a few days now, but I simply don't understand what's happening: I have a Serializable class with 2 main methods, serialize() which just stringifies the instance and wake(serialized) which should wake up or "resurrect" an instance.

class Serializable {
  constructor() {}

  serialize() {
    return JSON.stringify(this);
  }

  wake(serialized) {
    // this is probably where the problem is and I don't really know how to approach it
    const unserialize = JSON.parse(serialized)
    return new this.constructor(unserialize)
  }
}

Then I declare User which extends from Serializable:

class User extends Serializable {
  constructor({
    firstName,
    lastName,
  }) {
    super();

    this.firstName = firstName;
    this.lastName = lastName;
  }
}

I create a new User:

let newUser = new User({
firstName: "Solid",
lastName: "Snake",
})

I serialize newUser and for example clarity I delete the instance:

const serialized = newUser.serialize()
newUser = null

Now I want to wake up the instance using the serialized constant:

const wakeUp = new User.wake(serialized)

This is where it fails. Error in Quokka is Cannot destructure property 'firstName' of 'undefined' as it is undefined. Error in console is the TypeError from the title.

  • The last part is what causing the issue. This is expected because your class depends on the properties `firstName`, and `lastName` in the constructor, plus you're de-structuring them hence you're getting this error. – Hiren Feb 15 '23 at 08:18
  • `firstName = "Solid"` and `lastName = "Snake"` should be `firstName : "Solid"` and `lastName : "Snake"` for an object literal. And a comma is missing too between them. Don't type code when asking questions, but copy-paste. – tevemadar Feb 15 '23 at 08:23
  • Thanks, guys. @tevemadar yes, that was exactly what happened, lol. I mistyped when I was typing the code. – Iroquois Pliskin Feb 15 '23 at 16:05

1 Answers1

0

Besides the object literal typo:

class Serializable {
  constructor() {}

  serialize() {
    const name = this.constructor.name;
    return JSON.stringify(this);
  }

  static wake(serialized) {                               // 'static' added
    const unserialize = JSON.parse(serialized);
    return new this.prototype.constructor(unserialize);   // 'prototype' added
  }
}
class User extends Serializable {
  constructor({
    firstName,
    lastName,
  }) {
    super();

    this.firstName = firstName;
    this.lastName = lastName;
  }
}

let newUser = new User({
  firstName: "Solid", // no =, but ':' , also ','
  lastName: "Snake" // no =, but ':'
})

const serialized = newUser.serialize();
newUser = null;

const wakeUp = User.wake(serialized); // no 'new', it's not a constructor
console.log(wakeUp);
tevemadar
  • 12,389
  • 3
  • 21
  • 49