REST APIs allow React Native applications to communicate with servers using HTTP. They are commonly used to fetch data, send user input, authenticate users, and synchronize mobile apps with backend services.
In React Native, REST APIs are usually consumed using the built-in fetch() function or third-party libraries like Axios. The API endpoint returns JSON data that can be converted into JavaScript objects.
// Fetching data from a REST API using fetch()
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});
The API returns a list of posts in JSON format. The response.json() method parses the response, and the resulting JavaScript object is logged to the console.
You can connect this API call to a button or useEffect hook in React Native to fetch data when the screen loads or when the user taps a button.
Below is the React Native code logic, followed by a Live Simulation:
// Example using useEffect to call API on screen load
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(users => {
console.log(users);
});
}, []);
Click the button below to perform a real fetch request to a public API.
catch()