In this tutorial, we will discuss how you can integrate APIs into your React Native apps using the fetch API to retrieve data. APIs (Application Programming Interfaces) allow us to interact with other software. They are particularly useful for fetching data from a server and display it in your app.
By the end of this tutorial, you will understand how to:
Before proceeding, make sure you have a basic understanding of JavaScript and React Native. Familiarity with ES6 syntax, specifically promises and async/await, will be beneficial but not necessary.
To fetch data from an API, we will use the fetch API, a promise-based mechanism. A 'Promise' is an object representing the eventual completion or failure of an asynchronous operation.
Fetch API provides a global fetch() method that you can use to read resources across the network. This method returns a Promise that you can use to retrieve the response of the request.
Here is a simple example:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log('Error:', error));
Let's fetch some data from an API and display it in our React Native component. We'll use the JSON placeholder API, which provides fake data for testing and prototyping.
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
const App = () => {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<View>
{data.map(item => (
<Text key={item.id}>{item.title}</Text>
))}
</View>
);
};
export default App;
In the above code, we are fetching data when the component is first rendered using the useEffect hook. Then we set the fetched data to our state variable using the useState hook. Finally, we map over the data array to display each item's title.
Here's another example where we fetch data from an API that requires an API key.
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
const App = () => {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://api.example.com/data', {
headers: {
'API-Key': 'your-api-key'
}
})
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<View>
{data.map(item => (
<Text key={item.id}>{item.title}</Text>
))}
</View>
);
};
export default App;
In this code, we add a headers object to the fetch request to include the API key.
In this tutorial, we learned how to fetch data from an API using the fetch API and display it in a React Native app. We also learned how to use the useEffect and useState hooks to handle side effects and maintain state in our application.
To learn more, you can read the Fetch API documentation and the React Native documentation.
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
const App = () => {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => setUsers(users));
}, []);
return (
<View>
{users.map(user => (
<View key={user.id}>
<Text>{user.name}</Text>
<Text>{user.email}</Text>
</View>
))}
</View>
);
};
export default App;
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
const App = () => {
const [weather, setWeather] = useState(null);
useEffect(() => {
fetch('https://api.openweathermap.org/data/2.5/weather?q=YourCity&appid=YourAPIKey')
.then(response => response.json())
.then(weatherData => setWeather(weatherData));
}, []);
return (
<View>
{weather && (
<Text>Current temperature: {weather.main.temp}</Text>
)}
</View>
);
};
export default App;
Remember to replace 'YourCity' and 'YourAPIKey' with your city name and OpenWeatherMap API key, respectively.