0

I've got a functional component which has state with an object of a specific class:

import React from "react";
import { ReactElement } from "react-native/node_modules/@types/react";
import { useState } from "react";
import { Text, View } from "react-native";
import MyClass from "./MyClass";

export default function FunCompWithState(): ReactElement {
  const [myClass, setMyClass] = useState<MyClass>(new MyClass());
  myClass.setTitle("New Title");

  console.log("typeof:                " + typeof myClass);
  console.log("object value:          " + myClass);
  console.log("object variable title: " + myClass.getTitle());
  console.log("object variable value: " + myClass.getValue());

  return (
    <View><Text>{myClass.getValue()}</Text></View>
  );
}

If it's helpful, this is my class definition:

export default class MyClass {
  private title: string = "";
  private value: number = 1;

  // Getters/Setters...
}

When this renders, I get the following in my logs:

❌    typeof:                object
❌    object value:          [object Object]
✅    object variable title: New Title
✅    object variable value: 1

But I would expect something like this:

✅    typeof:                MyClass
✅    object value:          {"title":"New Title","value":1}
✅    object variable title: New Title
✅    object variable value: 1

Is there a way to have useState respect the class of my state object?

Austin Brown
  • 830
  • 12
  • 24
  • 1
    [`typeof` only returns known possible values](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#description), it will not return your class name. If you want to check if an object is instance of your class, you can do it with [`instanceof`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof). eg `if (myClass instanceof MyClass)` – Ugur Eren Nov 11 '21 at 17:27
  • Ahh, interesting. Thanks! I also found out that I can [print my class name](https://stackoverflow.com/a/36643177/5476186) with `myClass.constructor.name`, so that's helpful for me when I'm debugging. – Austin Brown Nov 11 '21 at 17:52

0 Answers0