I am new to React Native and I am trying to create an application with it.
The problem is when I try to display the data in the application.
I am trying to consume a REST API to be able to display the data but it is not showing me anything. Besides this it does not show me what the error is so I am confused.
I think it's like I'm consuming the API but I can't find the error.
This would be my code:
import { StatusBar } from 'expo-status-bar';
import React, { useEffect, useState, useContext } from 'react';
import { StyleSheet, Text, View, FlatList, Image} from 'react-native';
const MORE_ICON = Platform.OS === 'ios' ? 'dots-horizontal' : 'dots-vertical';
import { Appbar } from 'react-native-paper';
import { Platform } from 'react-native';
import { Searchbar } from 'react-native-paper';
import { Avatar, Button, Card, Title, Paragraph } from 'react-native-paper';
import { render } from 'react-dom';
const API_ENDPOINT = 'https://localhost:5001/api/Medicines/';
export default function App () {
const [searchQuery, setSearchQuery] = React.useState('');
const onChangeSearch = query => setSearchQuery(query);
const [data, setData] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
fetch(API_ENDPOINT)
.then(response => response.json())
.then(results => {
setData(results);
})
.catch(err => {
setError(err);
});
}, []);
return (
<View >
<Appbar.Header>
<Appbar.Content title=" Medicine" />
</Appbar.Header>
<Searchbar
placeholder="Search"
onChangeText={onChangeSearch}
value={searchQuery}
/>
<FlatList
data={data}
keyExtractor={item => item.id}
renderItem={({ item }) => (
<Card>
<Card.Content>
<Title>{`${item.name.id}`}</Title>
<Paragraph></Paragraph>
</Card.Content>
<Card.Cover />
<Card.Actions>
<Button>info</Button>
</Card.Actions>
</Card>
)}
/>
</View>
)
}
UPDATE Add two if conditions, each returning a JSX for two different scenarios. First, when the data is fetched, a loading indicator is displayed. Second, when there is an error, an error message is displayed.
But it shows me the scenario of the error "Error fetching data... Check your network connection!"
export default function App() {
// state variables defined
// fetch data using useEffect
if (isLoading) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<ActivityIndicator size="large" color="#5500dc" />
</View>
);
}
if (error) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ fontSize: 18}}>
Error fetching data... Check your network connection!
</Text>
</View>
);
}
// ...
}