Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

React-Native Loading Class Object from AsyncStorage.getItem()

$
0
0

I'm trying to load data from AsyncStorage, but I'm having trouble handling the data as classes. For instance:

import AsyncStorage from "@react-native-async-storage/async-storage";function loadMyClass() {  const myClass = new MyClass();  AsyncStorage.setItem("@my.class", JSON.stringify(myClass)).then(() => {    load<MyClass>("@my.class").then((mc) => {      console.log("value:");      console.log(mc);      console.log("type:");      console.log(typeof mc);    });  });}async function load<T>(key: string) {  return AsyncStorage.getItem(key).then((json) => {    if (json != null) {      const obj = JSON.parse(json) as T;      return obj;    }    return null;  });}class MyClass {  private value: string = "abc";}

And then when I call loadMyClass(), I get this printed to the console:

value:Object {"value": "abc",}type:object

How can I cast my plain objects to a class and use them as a class?

Also - I know of class-transformer, but I've ran into some issues with it that I don't like so I'd prefer a pure Typescript solution.


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>