Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I want to map my JSON data into flatlist so that i can list out my data from database. is it possible to do so or are there any other ways to do it?
I had tried this for whole day and hope could be fix now.
This is my JSON:
{"-M1ytAolVL1xdnO0dXjD": {"Favourite": false, "ItemIdentity": "Qjwj", "ItemName": "Sjsj", "ItemQuantity": "1"}, "-M1ytGOJD62TwwEWOmMu": {"Favourite": true, "ItemIdentity": "This is my thing", "ItemName": "Acer laptop", "ItemQuantity": "12"}}
This is my flatlist code:
render() {
console.log(this.state.retrieveData.id)
return (
<Text>A</Text>
<FlatList data={this.state.retrieveData}
renderItem={({ item }) => (
<ListItem title={item.Favourite} />
<Text>B</Text>
</FlatList>
</View>
–
–
componentDidMount() {
// fetch your json here
const json = {"-M1ytAolVL1xdnO0dXjD": {"Favourite": false, "ItemIdentity": "Qjwj", "ItemName": "Sjsj", "ItemQuantity": "1"}, "-M1ytGOJD62TwwEWOmMu": {"Favourite": true, "ItemIdentity": "This is my thing", "ItemName": "Acer laptop", "ItemQuantity": "12"}};
const list = [];
for(const k in json) {
list.push({
id: k,
...json[k],
this.setState({retrieveData: list});
render() {
return (
<Text>A</Text>
<FlatList data={this.state.retrieveData}
renderItem={({ item }) => (
<ListItem title={item.Favourite} />
<Text>B</Text>
</FlatList>
</View>
For the very first you could parse raw JSON string:
const rawData = JSON.parse('{"-M1ytAolVL1xdnO0dXjD": {"Favourite": false, "ItemIdentity": "Qjwj", "ItemName": "Sjsj", "ItemQuantity": "1"}, "-M1ytGOJD62TwwEWOmMu": {"Favourite": true, "ItemIdentity": "This is my thing", "ItemName": "Acer laptop", "ItemQuantity": "12"}}')
then transform into array of values:
const data = Object.values(rawData);
// will produce
{"Favourite": false, "ItemIdentity": "Qjwj", "ItemName": "Sjsj", "ItemQuantity": "1"},
{"Favourite": true, "ItemIdentity": "This is my thing", "ItemName": "Acer laptop", "ItemQuantity": "12"}
Important: You should not do it inside render()
. Fill free to move such transformation near to fetching.
And then use data in render:
render() {
console.log(this.state.data)
return (
<Text>Data</Text>
<FlatList data={this.state.data}
renderItem={({ item }) => (
<ListItem title={item.Favourite} />
</View>
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.