The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
This kind of functionality was previously achieved using XMLHttpRequest.
Fetch deals with Request and Response objects.
Fetch can be used minimum one argument. It returns one Promise object. It resolves to the response to that object. Once we get the Response, we can access other body params.
Other arguments:
fetch also takes one second argument that can be used to customize the request. We can change the type of request like ‘POST’, ‘GET’ , ‘PUT’ etc. and also we can customize the header and body of the request. For example :
fetch('https://api.mywebsite.url/v1/postdata', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
param1: 'value1',
param2: 'value2',
}),
});
In this example above, we are fetching the data and converting the data to ‘json’ using its JSON.
In this example below, we are making one ‘POST’ request with a header and body values. The body is of type JSON.
fetch('https://api.mywebsite.url/v1/postdata', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
param1: 'value1',
param2: 'value2',
}),
});
Request properties and methods:
Request() constructor is used to create a new Request object. If you are receiving the Request object access various properties of the object. You can its find below those properties and a brief details of each-
Properties(readonly)
Request.cache: get the cache mode of the request.
Request.context : get the context of the request
Request.credentials: get the credentials of the request
Request.destination : get the request destination
Request.headers : get the header object
Request.integrity : get the integrity value of the request
Request.method: get the request method e.g. GET, POST, PUT etc.
Request.redirect : get the mode how redirect is handled
Request.referrer: get the referrer of the request
Request.referrerPolicy : get the referrer policy of the request
Request.url : get the url of the request
Methods
Below are some methods of Request object that you can use readily.
Request.clone() : this is used to clone the current request object.
Body.arrayBuffer() : returns one promise, to resolve with an body object of type ArrayBuffer
Body.blob() : returns one promise, to resolve with an body object of type Blob
Body.formData() : returns one promise, to resolve with an body object of type FormData
Body.json() : returns one promise, to resolve with an body object of type Json
Body.text() : returns one promise to resolve with an body object of type Text
Response properties and methods:
Similar to Request, Response object also has some properties and methods, which you can check below-
Properties(readonly)
Response.headers : get the headers object of the response
Response.ok : Boolean value to define if the response is success or not. A response is called success if the response is in the range of 200 to 299
Response.redirected : Defines if it is a redirected response
Response.status : status code of the response
Response.statusText : status message or text representation of the response value.
Response.type : type of the response
Response.url : the url of the response
Response.useFinalURL : Boolean value that defines if it is the final URL of the response
Body.body : A simple getter used to expose a ReadableStream of the body contents.
Body.bodyUsed : Stores a Boolean that declares whether the body has been used in a response yet
Methods
Response.clone() : creates the clone of the response object.
Response.error() : returns one response object with a network error
Response.redirect() : creates one response object with new url Response implements Body. So, it also contains the same Request Body methods we have defined above.
Async
We can also use async-await while fetching like below :
async function getJsonData() {
try {
let res = await fetch(
'https://facebook.github.io/react-native/movies.json',
);
let json = await res.json();
return json.data;
} catch (error) {
console.error(error);
}
}
Handling response data:
As explained above, we can handle the response using the Promise object returned by fetch. We can either use ‘then’ to handle this promise or any ‘async await’ function.
Example:
In the example below implemented in TypeScript we will be getting the current exchange rate EUR to USD & GBP consuming an API
you can download the project from:
import React, {Component} from 'react';
import {View, Text, StyleSheet, ActivityIndicator} from 'react-native';
interface IState {
curexch: currentExchange | null;
}
type Props = null;
type currentExchange = {
base: string;
date: string;
rates: rates;
};
type rates = {
GBP: number;
USD: number;
};
export default class App extends Component<Props, IState> {
constructor(props: Props) {
super(props);
this.state = {curexch: null};
}
public componentDidMount()
{
this.getCurExFromApi();
}
public getCurExFromApi = () => {
fetch('https://api.ratesapi.io/api/latest?symbols=USD,GBP')
.then((response) => response.json())
.then((json: currentExchange) => {
this.setState({curexch: json});
})
.catch((error) => {
console.error(error);
});
};
// renders the content for the app
render() {
return this.state.curexch === null ? (
<ActivityIndicator />
) : (
<View style={styles.container}>
<View>
<Text style={styles.headerText}>
Base Currency: {this.state.curexch.base}
</Text>
</View>
<View style={styles.ShapeView}>
<Text style={styles.rates}>USD: {this.state.curexch.rates.USD}</Text>
<Text style={styles.rates}>GBP: {this.state.curexch.rates.GBP}</Text>
</View>
</View>
);
}
}
// CSS styles used
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
borderColor: '#C8C8C8',
backgroundColor: '#000000',
},
headerText: {
fontSize: 30,
textAlign: 'center',
margin: 10,
color: '#C8C8C8',
fontWeight: 'bold',
},
rates: {
top: 90,
left: 60,
fontSize: 25,
color: '#C8C8C8',
},
ShapeView: {
width: 270,
height: 270,
borderRadius: 4,
borderWidth: 10,
borderColor: '#C8C8C8',
backgroundColor: '#000000',
},
});