Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
Discover Mentorship
The above is an affiliate link, if you buy the book I'll get a small commission at no extra charge to you.
Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
The above is an affiliate link, if you buy the book I'll get a small commission at no extra charge to you.
Home/Pills/ Pill - React fetch hook/
Home/Pills/Pill - React fetch hook/

React fetch hook

Jan 30, 2021

DESCRIPTION

Let's create a custom hook for fetching data with the browser fetch which we'll use for getting some Pokemons from pokeAPI.

Preview

Fetch them all!

React - useFetch.js
React - App.js

Summary

  • We used a combination of useReducer and useEffect hooks to create our custom useFetch hook.
  • Additionally, browser fetch with async/await and try...catch was used to get the data from an API through an endpoint.
  • Then, we created an example application using pokeAPI and Material UI.
  • As fetch requires a little bit of boilerplate and doesn't catch all the possible errors (need to use .ok check), you might consider axios instead for the useFetch hook (and call it e.g. useApi 😀)
  • There is a way to completely omit this custom hook by using react-query 🙈. It's an amazing library for data fetching with support for cache, etc.
  • I didn't mention Redux or MobX at all, as over time I value decentralized state more and there are solutions like react-query for data fetching. Still, you could use any of these two if you're experienced with them instead of the custom hook we created.
  • Feel free to extend the app as you need - maybe create astonishing Pokedex online? (just throwing an idea)
THE GUIDE TO BEAT FRONTEND INTERVIEW
From time to time, I'll send you messages about new blog posts, knowledge pills, and mentoring promotions. Only valuable information, no spam included. You can unsubscribe at any time.
slack
Let's build a community that will help each other.
spread the word
You don't need to, it's okay...