0

I have been trying to work this out for a VERY long time, but I just cannot. I do not understand why an array, whose contents I console.log, and clearly see it is not empty, and has the elements I want in it, is not being rendered on the page when I run my react native app. My code is below, please help guys

import React, { useEffect } from "react";
import AsyncStorage from "@react-native-community/async-storage";
import { View, Text } from "react-native";

export default function PaymentsScreen() {

  const [renderedData, setRenderedData] = React.useState(new Array<string>());

  const getData = async () => {
    try {
      const keys = await AsyncStorage.getAllKeys();
      const result = await AsyncStorage.multiGet(keys);
      return result;
    } catch (e) {
      console.log(e);
    }
  };

  async function parseData() {
    const payments = await getData();

    if (payments) {

        const res = payments
        .filter((e: any[]) => e[1] && e.includes('{'))
        .map((e: any[]) => e[1]);
        
        setRenderedData(res);
    }

    return renderedData;
  }
  
  React.useEffect(() => {
    parseData()
  });
 
  return (

    <View>

      {renderedData.map(data => <Text>{data}</Text> )}

    </View>
    
  );
}

Henry
  • 11
  • 3

3 Answers3

1

dont push directly the data on renderedData

you should use setRenderedData

React.useEffect(() => {
   async function fetchData() {
      try {
        const keys = await AsyncStorage.getAllKeys();
        const result = await AsyncStorage.multiGet(keys);
        const res = result
           .filter((e: any[]) => e[1] && e.includes('{'))
           .map((e: any[]) => e[1]);
        setRenderedData(res);
      } catch (e) {
        console.log(e);
      }
   }
   fetchData();
}, []);
Leonardo Lima
  • 474
  • 5
  • 12
0

Inside your render function, since the data you are trying to render is an array, you need to loop through them to render each as text node.

 return (
      <View>
          { renderedData.map((item, key)=>(
            <Text key={key}> { item } </Text>)
          )}
      </View>
        );
Vijay122
  • 884
  • 8
  • 12
0

First of all, it is bad practive to change the state directly. State should be considered as immutabe (see explantion).

so change

renderedData.push(eachPayment[1]);

to

setRenderedData([...renderedData, eachPayment[1]);



Now, to the problem you are having, try to change

<Text> {renderedData} </Text>

to

{renderedData.map(data => <Text>{data}</Text> )}



try also change useEffect like this:

React.useEffect(() => {
    if(renderedData.length === 0) {
        parseData();
    }
},[]);
D10S
  • 1,468
  • 2
  • 7
  • 13