Skip to content

Instantly share code, notes, and snippets.

@PavanKu
Created May 20, 2019 02:55
Show Gist options
  • Save PavanKu/c870cb083891c489af4b1413850e4817 to your computer and use it in GitHub Desktop.
Save PavanKu/c870cb083891c489af4b1413850e4817 to your computer and use it in GitHub Desktop.
React native Ajax example
import React from 'react';
import { View, Text, Image, ActivityIndicator, StyleSheet, FlatList } from "react-native";
const initialState = { pictures: [] }
class PictureList extends React.Component {
constructor(props) {
super(props);
this.state = initialState;
}
async fetchPictures() {
const api = 'https://picsum.photos/v2/list';
const fetchResponse = await fetch(api);
const pictures = await fetchResponse.json();
this.setState({ pictures });
}
componentDidMount() {
this.fetchPictures();
}
render() {
const { pictures } = this.state;
if (!pictures.length) { return (<ActivityIndicator />); }
return (
<View>
<FlatList data={pictures} renderItem={({item}) => (
<View style={styles.container} key={item.id}>
<Image style={styles.image} source={{uri: item.download_url}} />
</View>
)} keyExtractor={(item, id) => item.id}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
borderColor: '#ccc',
borderWidth: 1,
borderRadius: 5,
backgroundColor: '#eaf7fd',
marginBottom: 15,
},
image: {
margin: 5,
borderRadius: 5,
width: 300,
height: 300,
}
});
export default PictureList;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment