'React Native fetch data and display it

I am new to react native and have a big problem since a few days now. I try to fetch the data from an Wordpress API and then return it so that I can display it. But it is not working.

What I receive is a json with objects which contain contact details:

{
  "data": {
    "error_code": 0,
    "data_values": [
      [{
          "kontakte_id": "1",
          "kontakte_unternehmen": "47",
          "kontakte_anrede": "Frau",
          "kontakte_titel": "Dr.",
          "kontakte_infos": "Testinfo",
          "kontakte_vorname": "erterter",
          "kontakte_nachname": "ertreter",
          "kontakte_position": "CTO",
          "kontakte_strasse": "Pariser Straße, 2",
        },
        {
          "kontakte_id": "2",
          "kontakte_unternehmen": "47",
          "kontakte_anrede": "Herr",
          "kontakte_titel": "Kein Titel",
          "kontakte_infos": "Architekten",
          "kontakte_vorname": "Mister",
          "kontakte_nachname": "Man",
          "kontakte_position": "CEO",
          "kontakte_strasse": "blanaka",
        }
      ]
    ]
  }
}

The first thing I want to know is how to display the objects in a kind of list (like for each).

The second thing is I have an error code. So I want to check if there is an error and then return the error or the objects to display it.

I tried several ways and looked at different post in the internet but could not find a solution. Please hep me. Here is my code:

import React, { useState, useEffect } from "react";
import {
  Alert,
  View,
  Text,
  Modal,
  StyleSheet,
  Pressable,
  ListView,
  FlatList,
  Button,
} from "react-native";
import { createStackNavigator } from "@react-navigation/stack";
import { theme } from "../../core/theme";
import clientConfig from "../../../client-config";

const Stack = createStackNavigator();

const ModalComponent = ({ modalVisible, setModalVisible, children }) => {
  return (
    <Modal
      animationType="slide"
      transparent={true}
      style={styles.centeredView}
      visible={modalVisible}
      onRequestClose={() => {
        Alert.alert("Modal has been closed.");
        setModalVisible(!modalVisible);
      }}
    >
      {children}
    </Modal>
  );
};

export default function KontakteStackNavigator({ navigation }) {
  const [modalVisible, setModalVisible] = useState(false);
  const [modal2Visible, setModal2Visible] = useState(false);
  const [modal3Visible, setModal3Visible] = useState(false);
  const [data, setData] = useState([]);

  const get_contacts = async () => {
    try {
      const siteUrl = clientConfig.siteUrl + "/wp-json/v1/contacts";
      const response = await fetch(siteUrl, {
        method: "GET",
        headers: {
          Authorization: "Bearer " + localStorage.getItem("token"),
        },
      });
      //console.log(JSON.stringify(response));
      if (response.status === 200) {
        let json = await response.json();
        const array = json.data;

        const kontakte = array.data_values;
        const error = array.error_code;

        if (error == 0) {
          setData(kontakte);
        } else {
          setData(1201);
        }
      } else {
        if (response.status === 503) {
          setModalVisible(true);
        }
        if (response.status === 403) {
          setModal2Visible(true);
        }

        throw new Error(`failed due to status code ${response.status}`);
      }
    } catch (err) {
      console.log(err);
    }
  };

  if (localStorage.getItem("token") != null) {
    //get_contacts();

    return (
      <View>
        <Text>lfkf</Text>
      </View>
    );
  } else {
    navigation.navigate("Dashboard");
  }

  return (
    <>
      <ModalComponent
        modalVisible={modalVisible}
        setModalVisible={(val) => {
          setModalVisible(val);
        }}
      >
        <View style={styles.centeredView}>
          <View style={styles.modalView}>
            <Text style={styles.modalText}>Fehler 503</Text>
            <Text style={styles.modalText}>
              Ein unbekannter Fehler ist aufgetreten!.
            </Text>
            <Pressable
              style={[styles.button, styles.buttonClose]}
              onPress={() => setModalVisible(!modalVisible)}
            >
              <Text style={styles.textStyle}>Ok</Text>
            </Pressable>
          </View>
        </View>
      </ModalComponent>

      <ModalComponent
        modalVisible={modal2Visible}
        setModalVisible={(val) => {
          setModal2Visible(val);
        }}
      >
        <View style={styles.centeredView}>
          <View style={styles.modalView}>
            <Text style={styles.modalText}>Fehler 403</Text>
            <Text style={styles.modalText}>
              Bitte loggen Sie sich erneut ein!
            </Text>
            <Pressable
              style={[styles.button, styles.buttonClose]}
              onPress={() => setModal2Visible(!modal2Visible)}
            >
              <Text style={styles.textStyle}>Ok</Text>
            </Pressable>
          </View>
        </View>
      </ModalComponent>

      <ModalComponent
        modalVisible={modal3Visible}
        setModalVisible={(val) => {
          setModal3Visible(val);
        }}
      >
        <View style={styles.centeredView}>
          <View style={styles.modalView}>
            <Text style={styles.modalText}>
              Ein unbekannter Fehler ist aufgetreten!
            </Text>
            <Pressable
              style={[styles.button, styles.buttonClose]}
              onPress={() => setModal3Visible(!modal3Visible)}
            >
              <Text style={styles.textStyle}>Ok</Text>
            </Pressable>
          </View>
        </View>
      </ModalComponent>
    </>
  );
}

const styles = StyleSheet.create({
  wrongPassword: {
    color: "red",
    fontSize: 16,
    lineHeight: 26,
    fontWeight: "bold",
    marginBottom: 20,
    textAlign: "center",
  },
  eyeContainer: {
    position: "relative",
    top: -47,
    right: -130,
    paddingBottom: 30,
  },
  forgotPassword: {
    width: "100%",
    alignItems: "flex-end",
    marginBottom: 24,
  },
  row: {
    flexDirection: "row",
    marginTop: 4,
  },
  forgot: {
    fontSize: 13,
    color: theme.colors.secondary,
  },
  link: {
    fontWeight: "bold",
    color: theme.colors.primary,
  },

  centeredView: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    marginTop: 22,
  },
  modalView: {
    width: 320,
    margin: 20,
    backgroundColor: "white",
    borderRadius: 20,
    padding: 35,
    alignItems: "center",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
  },
  button: {
    borderRadius: 5,
    width: 100,
    padding: 10,
    elevation: 2,
  },
  buttonOpen: {
    backgroundColor: "#F194FF",
  },
  buttonClose: {
    backgroundColor: "#1584a5",
  },
  textStyle: {
    color: "white",
    fontWeight: "bold",
    textAlign: "center",
  },
  modalText: {
    marginBottom: 15,
    textAlign: "center",
  },
});


Solution 1:[1]

You can use FlatList to render the data in list format:-

<FlatList
  data={data}
  keyExtractor={(item, index) => index + item.value}
  renderItem={({item, index})=>(
    <Text>{item.kontakte_vorname}</Text>
  )}/>

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 this.arjun