From the course: React Hooks

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Data fetching with a Fetch Hook

Data fetching with a Fetch Hook - React.js Tutorial

From the course: React Hooks

Start my 1-month free trial

Data fetching with a Fetch Hook

- [Instructor] So far we've fetched data with useEffect, and we've also loaded some state data with useContext. In this video, we're going to take a look at how to fetch data with a custom hook. So let's kind of think about the process of fetching data. If we go back to our index file and we get rid of some of this context stuff, what we're really trying to do is handle one of three states. So if the data isn't available yet, but is loading. We have a state for if we get the data, and we have a state for if there's an error. So since all of these states exist with the request, we can wrap this inside of a hook. Let's create a new file called useFetch. So useFetch is going to handle all of these different states. We first need to import useState and useEffect from React. And then this function is going to be exported. useFetch will take in a URI of some sort of API that we want to fetch from. And then again, we…

Contents