Updated April 15, 2023
Introduction to React Native Fetch
Fetching data from a data source is considered as a basic requirement of any mobile application. In order to retrieve data from a given URL, it provides fetch API, fetch API is a networking API which works in a similar way like a rest API, fetch API accepts URL of the source as an argument from which data needs to be fetched.
Syntax:
// import react component
import React, { Component } from 'react';
// create class
class <ClassName> extends Component {
performFetchOperation = () => {
this.setState({
// make changes in variables state as per your requirement
})
fetch("<URL of data source>")
// convert response in json format
.then(response => response.json())
// read response received
.then((responseJson) => {
// write code to handle response data received from fetch API
})
// catch error if occurred during fetch as per our requirement
.catch(error =>
// write code to handle error condition
)
}
}
The above syntax shows how to use fetch API in react native. In the above syntax we have defined a method that is responsible for performing fetch operation from a given data source.
Functions of React Native Fetch
Fetch can be used to retrieve data from a given URL source. Below given are the prominent functions.
1. Initialize Constructor of React Native Class
- First, we need to define two different states, one being a Boolean variable and other being an array into which data loaded by fetch API will be stored.
- The Boolean variable set to true in constructor signifies that data loading from URL has started.
- Here is how the constructor class having fetch implementation is defined.
Code:
constructor(props) {
super(props);
this.state = {
dataloadstarted: true, // boolean variable
dataReceivedFromFetch:[] // array of data
};
}
2. Write Implementation of React Native Class
- After the constructor is initialized successfully, we will write implementation of react native fetch API.
- For instance we will use componentDidMount method of react native lifecycle to write implementation of it as this method is called in the beginning of application. Implementation of fetch method in it involves handling response received from given URL as per our requirement.
- It provides catch clause whose purpose is to handle failure scenarios while fetching data from given URL.
3. Render Data Received from Fetch onto User Interface
- This is the final step involved in using fetch API.
- This step involves data received from API to be rendered on required user interface.
- This is generally done in render method of react native class.
Example of React Native Fetch
The below example gives a clear picture of the different steps involved in it:
Code:
import React from "react";
import {
StyleSheet,
View,
ActivityIndicator,
FlatList,
Text,
TouchableOpacity
} from "react-native";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
dataSource:[]
};
}
componentDidMount(){
fetch("https://dummy.restapiexample.com/api/v1/employees")
.then(response => response.json())
.then((responseData)=> {
this.setState({
loading: false,
dataSource: responseData.data
})
})
.catch(error=>console.log(error)) //to catch the errors if any
}
FlatListItemSeparator = () => {
return (
<View style={{
height: .5,
width:"100%",
backgroundColor:"rgba(0,0,0,0.5)",
}}
/>
);
}
renderItem=(data)=>
<TouchableOpacity style={styles.list}>
<Text style={styles.lightText}>Employee Name : {data.item.employee_name}</Text>
<Text style={styles.lightText}>Employee Salary : {data.item.employee_salary}</Text>
<Text style={styles.lightText}>Employee Age : {data.item.employee_age}</Text></TouchableOpacity>
render(){
if(this.state.loading){
return(
<View style={styles.loader}>
<ActivityIndicator size="large" color="#0c9"/>
</View>
)}
return(
<View style={styles.container}>
<View>
<Text> Employee Details</Text>
</View>
<FlatList
data= {this.state.dataSource}
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem= {item=> this.renderItem(item)}
keyExtractor= {item=>item.id.toString()}
/>
</View>
)}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#0c9"
},
loader:{
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#fff"
},
list:{
paddingVertical: 2,
margin: 5,
backgroundColor: "#fff"
}
});
In the above code we are fetching employee data from URL http://dummy.restapiexample.com/api/v1/employees and displaying employee data in a list view.
Output:
Recommended Articles
This is a guide to React Native Fetch. Here we discuss the Introduction, syntax , functions of React Native Fetch along with example and code implementation. You may also have a look at the following articles to learn more –