import React from ‘react’;
import { FlatList, ActivityIndicator,Alert, Text,Button,TextInput, View } from ‘react-native’;
export default class networkDemo extends React.Component{
state={
isLoading: true,
Movies:[] ,
title:‘Black Panther’,
releaseYear:‘2018’,
};
buttonPressHandler=()=>{
//Alert.alert(‘Clicked’);
this.setState({
isLoading:true
});
const Movies= {
title:this.state.title,
releaseYear:this.state.releaseYear
};
console.log(JSON.stringify(Movies));
console.log((Movies));
return fetch(“https://react-native-http.firebaseio.com/films.json”, {
method: “POST”,
body: JSON.stringify(Movies)
})
.catch(Err =>console.log(Err))
.then(res=> res.json())
.then(parsedRes =>{
this.setState({
isLoading: false,
});
console.log(parsedRes);
Alert.alert(‘Movie Saved’);
});
};
componentDidMount(){
//https://react-native-http.firebaseio.com/places.json
return fetch(‘https://react-native-http.firebaseio.com/films.json’)
.then((response) => response.json())
.then((parsedRes) => {
const movies = [];
for (let key in parsedRes) {
movies.push({
…parsedRes[key],
key: key
});
console.log(movies);
}
this.setState({
isLoading: false,
dataSource:movies,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
};
render(){
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return(
<View style={{flex: 1, paddingTop:20}}>
<TextInput value={this.state.title} onChangeText={(title)=>{this.setState({
title:title
})}} />
<TextInput value={this.state.releaseYear} onChangeText={(releaseYear)=>{this.setState({
releaseYear:releaseYear
})}} />
<Button onPress={this.buttonPressHandler} title=“Add movie” />
<FlatList
data={this.state.dataSource}
renderItem={({item}) => <Text>{item.title}, {item.releaseYear}</Text>}
keyExtractor={(item, index) => index}
/>
</View>
);
}
}
Reaact-native Networking – REST API With Firebase
Updated: Jun 9, 2020
Comments