React Native developers often encounter common tasks that require repetitive code, such as fetching data. To streamline this task, here is a custom hook: useFetch. This hook is not only simple and easy to use but also cater to edge cases, making your development process smoother.
useFetch Hook
The useFetch hook simplifies the process of fetching data from an API, managing the loading state, and handling errors gracefully. It even checks for network connectivity before attempting a fetch, ensuring your app remains robust in various conditions.
import { useState, useEffect } from 'react'; | |
import NetInfo from '@react-native-community/netinfo'; | |
const useFetch = (url) => { | |
const [data, setData] = useState([]); | |
const [error, setError] = useState(null); | |
const [loading, setLoading] = useState(true); | |
useEffect(() => { | |
const fetchData = async () => { | |
try { | |
// Check network status | |
const state = await NetInfo.fetch(); | |
if (!state.isConnected) { | |
throw new Error('No internet connection'); | |
} | |
const response = await fetch(url); | |
if (!response.ok) { | |
throw new Error(`HTTP error! status: ${response.status}`); | |
} | |
const result = await response.json(); | |
setData(result); | |
} catch (err) { | |
setError(err.message); | |
} finally { | |
setLoading(false); | |
} | |
}; | |
fetchData(); | |
}, [url]); | |
return { data, error, loading }; | |
}; | |
export default useFetch; |
Usage Example
const { data, loading, error } = useFetch('https://jsonplaceholder.typicode.com/users');
Top comments (0)