Friday 28 July 2023

REACT NATIVE - Flat List using axios and useEffect and api integration

 Day 3 

import React, {useState, useEffect} from 'react';
import axios from 'axios';

import {
View,
Image,
FlatList,
StyleSheet,
SafeAreaView,
Text,
StatusBar,
ActivityIndicator,
Platform,
} from 'react-native';

// create a component
const ProductsGridView = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);

useEffect(() => {
axios
.get('https://fakestoreapi.com/products')
.then(res => {
setData(res.data);
setLoading(true);
})
.catch(err => {
setLoading(true);
});
}, []);

if (loading) {
return (
<SafeAreaView style={styles.container}>
<Text
style={{
fontSize: 18,
padding: 10,
justifyContent: 'center',
alignItems: 'center',
}}>
Products List
</Text>

<FlatList
data={data}
renderItem={({item}) => (
<View style={styles.card}>
<Image
resizeMode="contain"
style={styles.imageThumbnail}
source={{uri: item.image}}
/>
<Text style={styles.title}>{item.title}</Text>

<Text style={styles.price}>{'$ ' + item.price}</Text>
</View>
)}
//Setting the number of column
numColumns={2}
keyExtractor={(item, index) => index.toString()}
/>
</SafeAreaView>
);
} else {
return (
<SafeAreaView style={styles.container}>
<ActivityIndicator size="large" />
</SafeAreaView>
);
}
};

// define your styles
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: StatusBar.marginTop || 0,
},

title: {
fontSize: 16,
marginTop: 10,
},

price: {
fontWeight: '600',
fontSize: 17,
marginTop: 10,
},

card: {
flex: 1,
elevation: 3,
margin: 5,
padding: 10,
backgroundColor: 'white',
borderRadius: 1,
elevation: 2,
shadowColor: 'grey',
shadowOpacity: 0.25,
shadowOffset: {width: 0, height: 2},
shadowRadius: 8,
overflow: Platform.OS === 'android' ? 'hidden' : 'visible',
},
imageThumbnail: {
justifyContent: 'center',
alignItems: 'center',
height: 150,
padding: 2,
margin: 5,
},
});

//make this component available to the app
export default ProductsGridView;


Screenshot







No comments:

Post a Comment