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

How to Update React Native Functional Component State from Storage

$
0
0

I've got this component which is attempting to set its state using an object loaded from storage:

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";import AsyncStorage from "@react-native-async-storage/async-storage";export default function FunCompWithState(): ReactElement {  const [myClass, setMyClass] = useState<MyClass>(new MyClass());  const promised = loadFromStorage();  // I've also try calling this in a useEffect()  promised.then(c => setMyClass(c));  return (<View><Text>{myClass.getTitle()}</Text><Text>{myClass.getValue()}</Text></View>  );}async function loadFromStorage(): Promise<MyClass | null> {  const jsonValue = await AsyncStorage.getItem("@main.myClass");  console.log(jsonValue);  if (jsonValue != null) {    return Promise.resolve(JSON.parse(jsonValue));  }  return Promise.resolve(null);}

In my test, this is what I've got:

import * as React from "react";import { act, render } from "@testing-library/react-native";import FunCompWithState from "../FunCompWithState";import MyClass from "../MyClass";import AsyncStorage from "@react-native-async-storage/async-storage";async function setup() {    const storedClass = new MyClass();    storedClass.setTitle("Stored Class");    storedClass.setValue(8);    await AsyncStorage.setItem("@main.myClass", JSON.stringify(storedClass));}it("Render FunCompWithState", () => {  act(() => {      setup();  });  const { debug } = render(<FunCompWithState />);  debug();});

When I run my test, the console.log(jsonValue) that I placed in the loadFromStorage function outputs the correct values: {"title":"Stored Class","value":8}. However, the rendered component doesn't seem to have the correct values:

<View><Text></Text><Text>        1</Text></View>

I would expect to be seeing this:

<View><Text>        Stored Class</Text><Text>        8</Text></View>

So how can I get the correct values to be in the rendered component? Is this a problem with how I'm updating my component state or is this an issue with how I'm testing the component?


Viewing all articles
Browse latest Browse all 6287

Trending Articles



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