When developing applications in React Native, one of the common tasks you'll encounter is fetching data from an API. Writing the fetching logic directly in your components can lead to messy and hard-to-manage code. This is where custom hooks come into the picture! Custom hooks can encapsulate particular logic, making your components cleaner and more reusable.
First, ensure that your development environment is ready. You'll need Node.js and React Native set up. If you haven't already set up a new project, you can create one with:
npx react-native init MyAwesomeApp
Change to the project directory:
cd MyAwesomeApp
We'll create a new file for our custom hook. It is a common practice to place hooks within a "hooks" directory.
hooks
inside your project root:mkdir hooks
Inside the hooks
directory, create a file called useFetch.js
.
Open useFetch.js
and start by writing the following code:
import { useState, useEffect } from 'react'; import { Alert } from 'react-native'; const useFetch = (url) => { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchData = async () => { try { const response = await fetch(url); if (!response.ok) { throw new Error('Network response was not ok'); } const result = await response.json(); setData(result); } catch (err) { setError(err.message); Alert.alert('Error', err.message); } finally { setLoading(false); } }; fetchData(); }, [url]); return { data, loading, error }; }; export default useFetch;
State Variables: We define three state variables: data
for storing the API response, loading
for indicating if data is being fetched, and error
for any potential error messages.
useEffect: This hook runs when the component mounts and whenever the url
changes. Inside it, we define an asynchronous function called fetchData
that handles the actual fetching.
Fetching Data: We make a GET request using the fetch
API. If the response is not OK (e.g., the status code is not in the range of 200-299), we throw an error. Otherwise, we convert the response to JSON and set it to the data
state.
Error Handling: If any errors occur during fetching, we catch them and set the error state, showing an alert to the user.
Loading State: The loading state is set to false
once the fetching is complete, whether successfully or due to an error.
Now that we have our custom hook set up, let’s see how to use it in a component. For this example, suppose we want to fetch and display a list of posts from a JSONPlaceholder API.
Open or create a file for your component, let's say Posts.js
.
Write the following code:
import React from 'react'; import { View, Text, FlatList, ActivityIndicator } from 'react-native'; import useFetch from '../hooks/useFetch'; const Posts = () => { const { data, loading, error } = useFetch('https://jsonplaceholder.typicode.com/posts'); if (loading) return <ActivityIndicator size="large" color="#0000ff" />; if (error) return <Text>Error: {error}</Text>; return ( <FlatList data={data} keyExtractor={(item) => item.id.toString()} renderItem={({ item }) => ( <View> <Text style={{ fontWeight: 'bold', fontSize: 16 }}>{item.title}</Text> <Text>{item.body}</Text> </View> )} /> ); }; export default Posts;
Fetching Data with the Hook: We call useFetch
with the API URL for fetching posts. This hook returns the data, loading state, and any errors.
Conditional Rendering: While data is being fetched, an ActivityIndicator
is displayed. If an error occurs, we show the error message.
Displaying Data: Once the data is successfully fetched, we use a FlatList
to render each post's title and body.
Finally, don’t forget to include this Posts
component in your main application file (like App.js
), and you’ll see the posts displayed when you run your app!
By structuring your API calls within a custom hook, you gain better reusability and cleaner components, making your code easier to read and maintain.
30/10/2024 | React Native
30/10/2024 | React Native
30/10/2024 | React Native
30/10/2024 | React Native
30/10/2024 | React Native
30/10/2024 | React Native
30/10/2024 | React Native