Home > other >  How to loop through a list returned by AsyncStorage
How to loop through a list returned by AsyncStorage

Time:01-22

I have following code returning a list from AsyncStorage like this:

[
  {"startTime":"111","endTime":"222"},
  {"startTime":"222","endTime":"333"}`enter code here`
]

const [data, setData] = React.useState();


const fetchValues = async () => {
    try {
      let listvalues = JSON.parse(await AsyncStorage.getItem("@registration"));
    } catch (err) {
      console.log("error in list getting: ", err);
    }
};

I tried typing

const listValues = await fetchValues(); 

but this gives an error

await is only allowed inside async functions),

so instead I tried:

React.useEffect(async () => {
    const scopeListValues = await fetchValues();
    setData(scopeListValues);
});

But that also gives an error

useEffect must not return anything besides a function, which is used for clean-up.

What I want to do is to loop though a list like this:

return (
  { registrations.map((item) => {
          return (
            <View key={item.key}>
              <Text style={styles.itemStyle}>{item.startTime}</Text>
            </View>
          );
     })
  }
)

CodePudding user response:

Basically, you can setData after fetched from Asyncstorage:

React.useEffect(()=>{
   AsyncStorage.getItem("@registration").then((_data) => {
      const data = _data && JSON.parse(_data);
      setData(data);
    });
},[])

Also, you are mapping through registrations but you set value to data so change it with data:

return (
  { data.map((item) => {
          return (
            <View key={item.key}>
              <Text style={styles.itemStyle}>{item.startTime}</Text>
            </View>
          );
     })
  }
)

CodePudding user response:

First fetch values need to return something

const fetchValues = async () => {
    let result = []
    try {
      let listvalues = JSON.parse(
        await AsyncStorage.getItem("@registration")
       );

    } catch (err) {
      console.log("error in list getting: ", err);
    }
    return result
}

Next, useEffect shouldnt be passed an async function. You can either use then and risk entering callback hell, or you could create and then call a async function in the useEffect:

// using then
React.useEffect(()=>{
   fetchValues.then(res=>{
     setData(Array.from(res))
   })
},[])
// creating async function
React.useEffect(()=>{
  const getData = async ()=>{
    const fetchResults = await fetchValues();
    const listData = Array.from(fetchResults);
    setData(listData)
  }
  // dont forget to call it
  getData()
},[])
  • Related