1.

How do you make Ajax call from React Native application? Give an example.

Answer»

We can use javascript to develop a mobile application using React native. calling an API is very much similar to how we make AJAX call in web application. Below example explains it in detail.

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;

In the above component, we are BUILDING a picture list component which makes API call and parse the response to show a list of images on a mobile screen. We can use the same fetch function to make an API call. Fetch method is introduced in the web as part of ES6 specification. Fetch is used in the same way we used to use on a web browser. First, we created a class-based component and assigned list of images as the state of a component. 

SINCE we haven’t made an API call yet that is why the initial state of out PictureList component will be an empty array. In the render method, if our state is empty which MEANS, we haven't received the response from a SERVER that is why we are showing ActivityIndicator component provided by react-native. It is default spinner displayed on the screen. When our component is mounted then componentDidMount React lifecycle method get invoked, there we will make an API call and once we receive the response we update the state of PictureList component. Once the state is updated, the render method will get called and we render a list of images using FlatList and Image component.



Discussion

No Comment Found