Home > OS >  Render a JSON sub object inside flatlist
Render a JSON sub object inside flatlist

Time:01-02

I am a student learning React Native. I try to print part of a JSON response in a flatlist, but after 2 days of trying and Googleing I unfortunately do not get any further.. But what exactly do I want? See the image below.

enter image description here

But the current situation shows the following and I don't get it like picture above.

enter image description here

Below you can see my flatlist code.

<FlatList
     data={data}
     vertical
     showsVerticalScrollIndicator={false}
     renderItem={renderItem}
     keyExtractor={(item) => item.id}
/>

const renderItem = ({ item }) => <Item data={item} />;

const Item = ({ data }) => (
    <View>
        <View
            style={{
                marginLeft: 30,
                marginRight: 30,
                paddingTop: 30,
                paddingBottom: 10,
                borderBottomWidth: 1,
                flexDirection: "row",
                justifyContent: "space-between",
            }}
        >
            <View>
                <Text
                    style={{
                        fontSize: FONTS.body5,
                    }}
                >
                    {data.products[0].name}
                </Text>
            </View>
            <View>
                <Text
                    style={{
                        fontSize: FONTS.h3,
                    }}
                >
                    {data.products[0].amount}{" "}
                    {data.products[0].amount_unit.short}
                </Text>
            </View>
        </View>
    </View>
);

Below you can see how I will soon be storing the data via an API.

const [data, setData] = React.useState({});
const [Runned, setRunned] = React.useState(false);
async function getValueSecure() {
    if (Runned == false) {
        let result = await SecureStore.getItemAsync("key");
        if (result) {
            fetch(
                "http://---/api/ingredients/?id="  
                    receipt?.id  
                    ".json",
                {
                    method: "GET",
                    headers: {
                        Authorization: "Token "   result.toString(),
                    },
                }
            )
                .then((resp) => resp.json())
                .then((data) => {
                    setData(data);
                    setRunned(true);
                })
                .catch((error) => console.log("error"));
        } else {
        }
    }
}
function Mount() {
    if (useIsFocused()) {
        getValueSecure();
    }
}
Mount();

And below you can see what is stored in variable data after running the code above.

Array [
  Object {
    "products": Array [
      Object {
        "ah_id": "0",
        "amount": 210,
        "amount_unit": Object {
          "id": 1,
          "name": "Gram",
          "short": "g",
        },
        "id": 1,
        "jumbo_id": "0",
        "name": "Riso Scotti buona idea risotto porcino",
        "picnic_id": "0",
      },
      Object {
        "ah_id": "0",
        "amount": 30,
        "amount_unit": Object {
          "id": 1,
          "name": "Gram",
          "short": "g",
        },
        "id": 2,
        "jumbo_id": "0",
        "name": "ongezouten roomboter",
        "picnic_id": "0",
      },
      Object {
        "ah_id": "0",
        "amount": 0.5,
        "amount_unit": Object {
          "id": 2,
          "name": "Eetlepel",
          "short": "el",
        },
        "id": 3,
        "jumbo_id": "0",
        "name": "zonnebloemolie",
        "picnic_id": "0",
      },
      Object {
        "ah_id": "0",
        "amount": 1,
        "amount_unit": Object {
          "id": 4,
          "name": "Stuk",
          "short": "st",
        },
        "id": 4,
        "jumbo_id": "0",
        "name": "biefstuk",
        "picnic_id": "0",
      },
      Object {
        "ah_id": "0",
        "amount": 1,
        "amount_unit": Object {
          "id": 3,
          "name": "Theelepel",
          "short": "tl",
        },
        "id": 5,
        "jumbo_id": "0",
        "name": "gedroogde oregano",
        "picnic_id": "0",
      },
      Object {
        "ah_id": "0",
        "amount": 325,
        "amount_unit": Object {
          "id": 1,
          "name": "Gram",
          "short": "g",
        },
        "id": 6,
        "jumbo_id": "0",
        "name": "koelverse Italiaanse roerbakgroente kastanjechampignons",
        "picnic_id": "0",
      },
  Object {
    "ah_id": "0",
    "amount": 5,
    "amount_unit": Object {
      "id": 1,
      "name": "Gram",
      "short": "g",
    },
    "id": 7,
    "jumbo_id": "0",
    "name": "verse selderij",
    "picnic_id": "0",
  },
  Object {
    "ah_id": "0",
    "amount": 45,
    "amount_unit": Object {
      "id": 1,
      "name": "Gram",
      "short": "g",
    },
    "id": 8,
    "jumbo_id": "0",
    "name": "Parmigiano Reggiano-poeder",
    "picnic_id": "0",
  },
],
"receipt": Object {
  "categories": Array [
    Object {
      "icon": "http://---/static/icons/cooking.png",
      "id": 1,
      "name": "Alles",
    },
    Object {
      "icon": "http://---/static/icons/halal.png",
      "id": 2,
      "name": "Halal",
    },
  ],
  "description": "Zoek je een gerecht waarbij het lijkt alsof je uren in de keuken hebt gestaan, maar je eigenlijk al in een kwartier klaar bent? Dan zit je bij deze risotto met biefstuk helemaal goed!",
  "duration": "15 min.",
  "id": 1,
  "kcal": "735 kcal.",
  "name": "Risotto met champignons, biefstuk en parmezaan",
  "photo": "http://---/static/images/baked-fries.jpg",
  "priceRating": 1,
  "rating": 4.8,
  "user": Object {
    "date_joined": "2021-12-28T22:59:10Z",
    "email": "[email protected]",
    "first_name": "---",
    "groups": Array [],
    "id": 17,
    "is_active": true,
    "is_staff": true,
    "is_superuser": true,
    "last_login": "2021-12-31T14:21:12Z",
    "last_name": "---",
    "password": "---",
    "user_permissions": Array [],
        "username": "---",
      },
    },
  },
]

So I want to have a flatlist that shows all products in this JSON response by name. However, I can't get it done. Hope someone here can help me further. I don't understand where I'm doing it wrong.

CodePudding user response:

Flatlist only found a single product on position 0. that's why the app renders only a single element.

Assume that the server returns this JSON-like response :

[
 {
    "products": [
     {
        "ah_id": "0",
        "amount": 210,
        "amount_unit":  {
          "id": 1,
          "name": "Gram",
          "short": "g",
        },
        "id": 1,
        "jumbo_id": "0",
        "name": "Riso Scotti buona idea risotto porcino",
        "picnic_id": "0",
      },
       {
        "ah_id": "0",
        "amount": 30,
        "amount_unit": {
          "id": 1,
          "name": "Gram",
          "short": "g",
        },
        "id": 2,
        "jumbo_id": "0",
        "name": "ongezouten roomboter",
        "picnic_id": "0",
      },
      {
        "ah_id": "0",
        "amount": 0.5,
        "amount_unit":  {
          "id": 2,
          "name": "Eetlepel",
          "short": "el",
        },
        "id": 3,
        "jumbo_id": "0",
        "name": "zonnebloemolie",
        "picnic_id": "0",
      },
     {
        "ah_id": "0",
        "amount": 1,
        "amount_unit":  {
          "id": 4,
          "name": "Stuk",
          "short": "st",
        },
        "id": 4,
        "jumbo_id": "0",
        "name": "biefstuk",
        "picnic_id": "0",
      },
      {
        "ah_id": "0",
        "amount": 1,
        "amount_unit": {
          "id": 3,
          "name": "Theelepel",
          "short": "tl",
        },
        "id": 5,
        "jumbo_id": "0",
        "name": "gedroogde oregano",
        "picnic_id": "0",
      },
       {
        "ah_id": "0",
        "amount": 325,
        "amount_unit":  {
          "id": 1,
          "name": "Gram",
          "short": "g",
        },
        "id": 6,
        "jumbo_id": "0",
        "name": "koelverse Italiaanse roerbakgroente kastanjechampignons",
        "picnic_id": "0",
      },
   {
    "ah_id": "0",
    "amount": 5,
    "amount_unit": {
      "id": 1,
      "name": "Gram",
      "short": "g",
    },
    "id": 7,
    "jumbo_id": "0",
    "name": "verse selderij",
    "picnic_id": "0",
  },
   {
    "ah_id": "0",
    "amount": 45,
    "amount_unit":  {
      "id": 1,
      "name": "Gram",
      "short": "g",
    },
    "id": 8,
    "jumbo_id": "0",
    "name": "Parmigiano Reggiano-poeder",
    "picnic_id": "0",
  },
],
"receipt": {
  "categories":[
    {
      "icon": "http://---/static/icons/cooking.png",
      "id": 1,
      "name": "Alles",
    },
    {
      "icon": "http://---/static/icons/halal.png",
      "id": 2,
      "name": "Halal",
    },
  ],
  "description": "Zoek je een gerecht waarbij het lijkt alsof je uren in de keuken hebt gestaan, maar je eigenlijk al in een kwartier klaar bent? Dan zit je bij deze risotto met biefstuk helemaal goed!",
  "duration": "15 min.",
  "id": 1,
  "kcal": "735 kcal.",
  "name": "Risotto met champignons, biefstuk en parmezaan",
  "photo": "http://---/static/images/baked-fries.jpg",
  "priceRating": 1,
  "rating": 4.8,
  "user":  {
    "date_joined": "2021-12-28T22:59:10Z",
    "email": "[email protected]",
    "first_name": "---",
    "groups": [],
    "id": 17,
    "is_active": true,
    "is_staff": true,
    "is_superuser": true,
    "last_login": "2021-12-31T14:21:12Z",
    "last_name": "---",
    "password": "---",
    "user_permissions":[],
        "username": "---",
      },
    },
  },
]



Here minified version on how you can render all products:

import * as React from 'react';
import { Text, View, StyleSheet,FlatList } from 'react-native';

import  data from  './response'
export default function App() {


  const renderItem = ({ item }) => <Item data={item} />;

const Item = ({ data }) => (
    <View>
        <View
            style={{
                marginLeft: 30,
                marginRight: 30,
                paddingTop: 30,
                paddingBottom: 10,
                borderBottomWidth: 1,
                flexDirection: "row",
                justifyContent: "space-between",
            }}
        >
            <View>
                <Text
                    style={{
                        fontSize: 12,
                    }}
                >
                    {data.name}
                </Text>
            </View>
            <View>
                <Text
                    style={{
                        fontSize: 13,
                    }}
                >
                    {data.amount}{" "}
                    {data.amount_unit.short}
                </Text>
            </View>
        </View>
    </View>
);
  return (
    <FlatList
     data={data[0].products}
     vertical
     showsVerticalScrollIndicator={false}
     renderItem={renderItem}
     keyExtractor={(item) => item.id}
/>

  )
}



I added Expo Snack for implementation result

https://snack.expo.dev/@emmbyiringiro/7c6685

  • Related