Lesson 3. Custom hooks and classic async pattern 5. Exercise & next steps
Our custom hook could be even more generic. What if we want to call another API?
Create another custom hook useApiCall taking as a parameter the URL we want to
call. Then rewrite useStarship using this custom hook.
Result
Click here to see the solution!
const useApiCall = (url) => {const [result, setResult] = useState(undefined)const [loading, setLoading] = useState(false)const [error, setError] = useState(false)useEffect(() => {setLoading(true)setError(false)let active = truefetch(url).then((res) => {if (res.ok) return res.json()else throw new Error('Not found')}).then((result) => {if (active) {setLoading(false)setResult(result)}}).catch((err) => {if (active) {console.error(err)setLoading(false)setError(true)}})return () => (active = false)}, [url])return { loading, error, result }}const useStarship = (starshipId) => {const { loading, error, result } = useApiCall(`https://swapi.dev/api/starships/${starshipId}/`)return { loading, error, starship: result }}
Next step
Custom hooks are handy since they allow you to extract and make reusable some logic from the rendering concern. You can find many hooks on the Internet; I listed in section Additional resources and links at the end of the guide some places where you can find ones. We’ll also create some new hooks for our needs in the rest of this guide, especially in lesson 12 to access some features offered by the browser’s API.
We know enough about hooks to take a small step back and look at how they work and some rules you have to respect when you use them.