1

I am currently getting data which is an array of objects from my local storage in following manner:

const [dataList, setDataList] = useState();
const getLocalItem = async () => {
    try {
      const jsonValue = await AsyncStorage.getItem('somekey');
      const list = JSON.parse(jsonValue);
      setDataList(list);
      console.log("list: ", dataList);
      return jsonValue != null ? JSON.parse(jsonValue) : null;
    } catch (e) {
      // error reading value
    }
  }

<TouchableOpacity onPress={getLocalItem}>
    <Text>Get file</Text>
</TouchableOpacity>

Following is getting consoled:

list:  
{0: {…}, 1: {…}, default: Array(2)}
0: {userId: 1, id: 1, title: "optio reprehenderit", body: " molestiae ut ut quas "}
1: {userId: 1, id: 2, title: "qui est esse", body: " aperiam non debitis possimus qui neque nisi nulla"}
default: (2) [{…}, {…}]
__proto__: Object

Now I am trying to map through this data to display it on my screen:

{
    dataList?.map(function (item, index) {
        return (
            <Text>{item.userId}</Text>
        );
    })
}

But I am getting error:

dataList.map is not a function

2 Answers 2

1

The dataList is an object and not an array. You cannot map through objects. And that's why you're getting this error.

You can use Object.values to get the value of object and consequently apply map on.

{Object.values(dataList).map(item => {
        return <Text>{item.title}</Text>;
      })}
Sign up to request clarification or add additional context in comments.

Comments

0

The map function can only be called on an array of values.

Solution:

[dataList]?.map(function (item, index) {
        return (
            <Text key={index}>{item.userId}</Text>
        );
    })

(also add a key to your child component when mapping).

Comments

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.