'JSON array not displaying correctly in React Native?
I have the following JSON data that's returned from an endpoint via a fetch() call:
[{"username":"\"Hyh\"","name":"GitHub","url_main":"https://www.github.com/","url_user":"","exists":"Illegal","http_status":"","response_time_s":"0.1234"},{"username":"\"Hyh\"","name":"GitLab","url_main":"https://gitlab.com/","url_user":"https://gitlab.com/\"Hyh\"","exists":"Available","http_status":"200","response_time_s":"0.14287607499954902"}]
I'm trying to display it like so:
import React, { useState, useEffect } from "react";
import {
View,
FlatList,
ActivityIndicator,
StyleSheet,
Text,
SafeAreaView,
} from "react-native";
const Results = ({ route, navigation }) => {
const { owner } = route.params;
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const fetchData = async () => {
const resp = await fetch(
"https://endpoint.com/search?user=" + JSON.stringify(owner.text)
);
const data = await resp.json();
setData(JSON.stringify(data));
setLoading(false);
};
useEffect(() => {
fetchData();
}, []);
const Item = ({ url }) => (
<View>
<Text>{url}</Text>
</View>
);
const renderItem = ({ item }) => <Item url={item.url_main} />;
return (
<View>
{loading ? (
<ActivityIndicator style={styles.loader} size="large" color="#7a16e4" />
) : (
<SafeAreaView>
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={(item) => item.response_time_s}
/>
</SafeAreaView>
)}
</View>
);
};
Any idea why nothing is rendering on my screen? I tried replacing my JSON with the JSON data here: https://reactnative.dev/docs/flatlist and it worked. I've confirmed data returns from the fetch through console.log(data).
Solution 1:[1]
setData(JSON.stringify(data));
you convert the object to string and pass it to the data prop in FlatList which is not correct.
the data prop should be an array
https://reactnative.dev/docs/flatlist#required-data
Your code should look like this
setData(data);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
