Data Fetching with React
Explore how to fetch live data in React by connecting to the Hacker News API using the native fetch method. Understand how to handle asynchronous data and update your component state with real API responses instead of mock data.
We'll cover the following...
We are currently fetching data, but it’s still pseudo data coming from a promise we set up ourselves. The lessons up to now about asynchronous React and advanced state management were preparing us to handle real-world scenarios. Mastering data fetching in React involves connecting your application to a real third-party API. We will use the reliable and informative Hacker News API to request popular tech stories.
Instead of using the initialStories array and getAsyncStories function (you can remove these), we will fetch the data directly from the API:
First, the API_ENDPOINT ,(A) is used to fetch popular tech stories for a certain query (a search topic). In this case, we fetch stories about React (B). Second, the native browser’s fetch API is used to make this request (B). For the fetch API, the response needs to be translated into JSON (C). Finally, the returned result follows a different data structure (D), which we send as payload to our component’s state.
In the previous code example we used JavaScript’s Template Literals for a string interpolation. When this feature wasn’t available in JavaScript, we’d have used the + operator on strings instead:
The complete code: