skip to Main Content

I used the following function inside the Flatlist data property but it is not rendering anything. why? I think an alternative is to set state inside the function and use the state as the flatlist data property, but in that case how do I set state whenever asyncstorage changes?

async function getFlatlistData(){
      try{
        const numbers = await AsyncStorage.getAllKeys();
        //numbers = 
        // ["{"key":"1678328476308","title":"Dog"}",
        //"{"key":"1678328921886","title":"Cat"}"]
        
  
        numbers.forEach(function myFunction(item, index, arr) {
                          arr[index] = JSON.parse(item);
                          arr[index]['key'] = Number(arr[index]['key'])
                        })
        numbers.sort((a, b) => b.key - a.key);
        console.log("running")
        return numbers

      } catch (error) {
        alert(error)
      }
      
    }
return (
    </View>
       <FlatList 
          data={getFlatlistData()} 
          renderItem={
            ({item}) => <Text>{item.title}</Text>
          } 
          keyExtractor={(item, index) => index.toString()}
       />
     </View>
    );
  }

2

Answers


  1. The FlatList component is not rendering anything because it is receiving a promise instead of an array of data.

    You need to use a useState to get the array before assigning to the Flatlist.

    import React, { useEffect, useState } from 'react';
    import { FlatList, Text, View } from 'react-native';
    import AsyncStorage from '@react-native-async-storage/async-storage';
    
    function App() {
     const [data, setData] = useState([]);
    
    useEffect(() => {
      async function fetchData() {
        try {
         const numbers = await AsyncStorage.getAllKeys();
         const parsedNumbers = numbers.map((item) => JSON.parse(item));
         const sortedNumbers = parsedNumbers.sort((a, b) => b.key - a.key);
         setData(sortedNumbers);
       } catch (error) {
        alert(error);
      }
    }
    
    fetchData();
    }, []);
    
    return (
     <View>
      <FlatList
        data={data}
        renderItem={({ item }) => <Text>{item.title}</Text>}
        keyExtractor={(item) => item.key.toString()}
      />
    </View>
    );
    }
    
    export default App;
    
    Login or Signup to reply.
  2. First: You need to use useState hook to render the components.
    Second: Your async function returns promise, not an array.

    import React from 'react';
    import { FlatList, Text, View } from 'react-native';
    import AsyncStorage from '@react-native-async-storage/async-storage';
    
    export default function FlatListData() {
    
        const [data, setData] = React.useState([]);
    
        const getFlatlistData = async() => {
            try{
                const numbers = await AsyncStorage.getAllKeys();
                if(numbers){
                    const newArr = [...JSON.parse(numbers)];
                    newArr.map((obj) => {
                        obj.key = Number(obj.key);
                    });
                    newArr.sort((a, b) => b.key - a.key);
                    setData(newArr);
                }
            }catch(e){
                throw e;
            }
        }
    
        React.useEffect(() => {
            getFlatlistData();
        }, []);
    
        return (
    
            <FlatList
            data={data} 
            renderItem={({item}) => <Text>{item.title}</Text>} 
            keyExtractor={(i, x) => x}/>
    
        );
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search