Fetching an API in React Native is quite similar to how you do it in regular React (for web), using fetch
, axios
, or other libraries. Here's a simple guide using the native fetch
API:
installing Axios library
npm install axios
Code ..
import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
const MyComponent = () => {
const [data, setData] = useState(null);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
setData(response.data);
})
.catch(error => {
console.error(error);
});
}, []);
return (
<View>
{data ? (
<>
<Text>{data.title}</Text>
<Text>{data.body}</Text>
</>
) : (
<Text>Loading...</Text>
)}
</View>
);
};
export default MyComponent;