04-Apr-2023
.
Admin
Hi friends,
Today, I explain react native rest API call example. I will show you how to rest api call in react native. we will help you react native rest API call.
This post will give you an idea about how to Make HTTP Request to Fetch the Data From Web APIs in React Native. Whenever you connect your application from the backend server (to get or post the data) you have to make an HTTP request. Here we will show you how to perform network tasks in React Native.
So, let's start following example:
Step 1 - Create project
expo init nicesnippets
Step 2 - install dependencies
yarn add react-native-paper
Step 3 - App.js
import React, { useState, useEffect } from 'react';
import { View, Text,SafeAreaView,StyleSheet, FlatList,Item } from 'react-native';
import { Avatar, Button, Card, Title, Paragraph } from 'react-native-paper';
const RestApiLink = () => {
const [Data, setData] = useState([])
const API = 'https://jsonplaceholder.typicode.com/posts';
const fetchPost = () => {
fetch(API)
.then((res) => res.json())
.then((res) => {
setData(res);
})
}
useEffect(() => {
fetchPost()
}, []);
const renderItem = ({ item: post }) => (
<Card style={styles.cardbox}>
<Text style={styles.title}>{post.title}</Text>
<Paragraph>{post.body}</Paragraph>
</Card>
);
return(
<SafeAreaView style={styles.container}>
<FlatList
data={Data}
renderItem={renderItem}
keyExtractor={Data => Data.id}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
textAlign: 'center',
justifyContent: 'center',
marginHorizontal: 10,
marginVertical: 15,
},
cardbox:{
marginVertical:8,
marginHorizontal:5,
padding: 10,
},
title:{
backgroundColor: '#e2e2e2',
fontWeight: 'bold',
textAlign: 'center',
borderRadius: 10,
paddingVertical: 5 ,
}
});
export default RestApiLink;
Step 4 - Run project
expo start
Output:
#React Native