1

I am trying to get my data from local storage (React Native Async Storage) and then push this data into an array (arrayItems) which is used for the flatlist data. My problem is that my data will not load in the flatlist and im not sure what to do. I believe the issue is because im getting the data from the local storage first after the flatlist has been rendered. I have tried using useEffect to get the data before rendering the flatlist but this does not seem to solve the issue.

My Code:

const [allKeys, setGetLocalStorageKeys] = useState([]);
let arrayItems= [];

const getLocalStorageKeys = async () => {
 try {
  setGetLocalStorageKeys(await AsyncStorage.getAllKeys());
 } catch (e) {}
};

const getItem = async (prop) => {
try {
  const item= await AsyncStorage.getItem(prop);
  return item != null ? JSON.parse(item) : null;
  } catch (e) {}
};

useEffect(() => {
try {
  getLocalStorageKeys();
  for (let i = 0; i < allKeys.length; i++) {
    arrayItems.push(getItem(allKeys[i]));
  }
} catch (e) {}
}, []);
return (
<View>
  <FlatList
    data={arrayItems}
    renderItem={({ item }) => <Text>{item}</Text>}
    keyExtractor={(item) => item}
  />
</View>

);

Local Storage https://github.com/react-native-async-storage/async-storage

2 Answers2

1

you can add another useEffect when you get allKeys it will call.

Like

        useEffect(() => {
           getLocalStorageKeys();
        }, []);
    
        useEffect(() => {
          const tempArr = [];
          if(allKeys.length > 0){
            for (let i = 0; i < allKeys.length; i++) {
            tempArr.push(getItem(allKeys[i]));
            }
          }
          setArrayItems(tempArr);
        }, [allKeys]);
Paresh Shiyal
  • 534
  • 4
  • 15
0

When you're using state that is changing in react-native make sure to use the useState hook. Because the screen will never rerender and show with the new data. This is because UseState causes your component to re-render each time there is a call to the update functions.

Do something like this below

const [allKeys, setGetLocalStorageKeys] = useState([]);
// Make sure to use useState for changing state in react
const [arrayItems,setArrayItems] = useState([]);


const getLocalStorageKeys = async () => {
 try {
  setGetLocalStorageKeys(await AsyncStorage.getAllKeys());
 } catch (e) {}
};

const getItem = async (prop) => {
try {
  const item= await AsyncStorage.getItem(prop);
  return item != null ? JSON.parse(item) : null;
  } catch (e) {}
};

useEffect(() => {
 const fetch = async = ()=>{
   try {
     getLocalStorageKeys();
     // Use a temp arr 
    const tempArr = [];
    for (let i = 0; i < allKeys.length; i++) {
      const value = await getItem(allKeys[i]);
       tempArr.push(value);
    }
     // Set the state
     setArrayItems(tempArr);
    } catch (e) {
     console.log(e);
    }
}
// Call function
fetch();
}, [allKeys]);

return (
<View>
  <FlatList
    data={arrayItems}
    renderItem={({ item }) => <Text>{item}</Text>}
    keyExtractor={(item) => item}
  />
</View>

carlosdafield
  • 1,479
  • 5
  • 16
  • Using your method, my flatlist still does not display anything. I am not sure if it is because my localstorage items are all objects that contain 3 values - name, image, email –  Jan 24 '22 at 19:22
  • Do me a favor and print out the length of the `arrayItems` and see if it ever is more than zero. – carlosdafield Jan 24 '22 at 19:35
  • console.log(arrayItems.length) after setArrayItems(tempArr) is 0 –  Jan 24 '22 at 20:03
  • console.log `getItem(allKeys[i])` and see if it's returning anything – carlosdafield Jan 24 '22 at 20:19
  • Doesnt console log anything, it might not be rendering anything –  Jan 24 '22 at 20:35
  • Put a console log in the catch so you can see the error I bet that's it. Also in javascript you meant to do `!==` not `!=`. Read the thing I posted below – carlosdafield Jan 24 '22 at 22:15
  • https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons – carlosdafield Jan 24 '22 at 22:15
  • I tried console logging the error but theres nothing in the console so im not sure whats happening. I believe the code is working as no errors are being logged but nothing is rendering. –  Jan 24 '22 at 22:55
  • In the useEffect, when i add allKeys for the dependencies i get an error where i get multiple promises. Promise { "_U": 0, "_V": 0, "_W": null, "_X": null, } –  Jan 24 '22 at 23:03
  • So what seems to be happening is that your not awaiting the promise – carlosdafield Jan 24 '22 at 23:04
  • One sec I'm gonna change up the code above – carlosdafield Jan 24 '22 at 23:04
  • Im not sure if you can use async function in useEffects, i cant seem to get it working to use await –  Jan 25 '22 at 00:18
  • You can for a fact. But your not suppose to await the async function inside the useEffect, and you can't make the useEffect async. – carlosdafield Jan 25 '22 at 00:21
  • Yo you should just watch a viedo on async storage, follow it exactly through, and then re write your code. – carlosdafield Jan 25 '22 at 00:23
  • I dont think the the problem is the async storage, when im not using useEffect i am able to get my data from the local storage. The problem maybe the way im using useEffect. –  Jan 25 '22 at 13:43