0

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>
          );
     })
  }
)
1
  • First of all, your fetchValues function does not return anything ... Commented Jan 21, 2023 at 16:12

2 Answers 2

1

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>
          );
     })
  }
)
Sign up to request clarification or add additional context in comments.

3 Comments

React.useEffect(() => { AsyncStorage.getItem("@registration").then((_data) => { const data = _data && JSON.parse(_data); setData(data); console.log("data: " + data); // prints data: [object Object],[object Object],[object Object],[object Object],[object Object] }); }, []); This prints out [object Object],[object Object]... is that intentional? Maybe I should leave out the && JSON.parse(_data); part ?
This prints out [object Object],[object Object]... is that intentional? Is that how arrays should look like? I thought it were more like this: [{object Object}, {object Object}] Anyway, it helped. Thanks!
Your data is object array so it should print like that but if you want to see data in it you can print it like this console.log(JSON.stringify(data)).
1

First fetch values need to return something

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

    } 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()
},[])

2 Comments

Thank you. I tried but I couldn't make it work so I went for the solution by Yakup Malikov instead.
Ah I forgot to add result=listdata in fetchValues

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.