How to use REST API in React Native Project
To use a REST API in a React Native project, you can use the fetch
API or a third-party HTTP client like axios
. Here is an example of how to make a GET request to a REST API using the fetch
API in a React Native app:
import React, { useState, useEffect } from 'react';
import { View, Text, ActivityIndicator } from 'react-native';
const App = () => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const json = await response.json();
setData(json);
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
};
fetchData();
}, []);
if (loading) {
return (
<View>
<ActivityIndicator />
</View>
);
}
if (error) {
return (
<View>
<Text>{error.message}</Text>
</View>
);
}
if (!data) {
return null;
}
return (
<View>
{data.map(item => (
<View key={item.id}>
<Text>{item.title}</Text>
</View>
))}
</View>
);
};
export default App;
In this example, the fetch
function sends a GET request to the https://jsonplaceholder.typicode.com/posts endpoint. The then
method is called on the response object returned by fetch
, and it parses the response as JSON.
Once the JSON data is received, you can use it in your React Native app by accessing the data
variable in the callback function passed to the then
method.
If you need to send other types of requests, such as POST or PUT, you can specify the request method in the options object passed as the second argument to the fetch
function. For example, here is how to send a POST request with a JSON body:
fetch('https://api.example.com/endpoint', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
// Request body data
}),
})
.then((response) => response.json())
.then((data) => {
// Do something with the data
});