Fetching Data
You will get to learn how to fetch data from an API using one the lifecycle methods that we discussed in the previous lesson.
We'll cover the following...
Now we’re prepared to fetch data from the Hacker News API. There was one lifecycle method mentioned that can be used to fetch data: componentDidMount()
. Before we use it, let’s set up the URL constants and default parameters to break the URL endpoint for the API request into smaller pieces.
import React, { Component } from 'react';import './App.css';const DEFAULT_QUERY = 'redux';const PATH_BASE = 'https://hn.algolia.com/api/v1';const PATH_SEARCH = '/search';const PARAM_SEARCH = 'query=';
In JavaScript ES6, you can use template literals for string concatenation or interpolation. You will use it to concatenate your URL for the API endpoint.
const DEFAULT_QUERY = 'redux';const PATH_BASE = 'https://hn.algolia.com/api/v1';const PATH_SEARCH = '/search';const PARAM_SEARCH = 'query=';// comment either ES5 or ES6// ES6const url1 = `${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${DEFAULT_QUERY}`;// ES5const url2 = PATH_BASE + PATH_SEARCH + '?' + PARAM_SEARCH + DEFAULT_QUERY;console.log(url1);// output: https://hn.algolia.com/api/v1/search?query=redux// outputconsole.log(url2);
This will keep your URL composition flexible in the future. Below, the entire data fetch process will be presented, and each step will be explained afterward.
import React, { Component } from 'react'class App extends Component {constructor(props) {super(props);this.state = {result: null,searchTerm: DEFAULT_QUERY,};this.setSearchTopStories = this.setSearchTopStories.bind(this);this.onSearchChange = this.onSearchChange.bind(this);this.onDismiss = this.onDismiss.bind(this);}setSearchTopStories(result) {this.setState({ result });}componentDidMount() {const { searchTerm } = this.state;fetch(`${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${searchTerm}`).then(response => response.json()).then(result => this.setSearchTopStories(result)).catch(error => error);}// ...}
First, we remove the sample list of items, because we will return a real list from the Hacker News API, so the sample data is no longer used. The initial state of your component has an empty result and default search term now. The same default search term is used in the input field of the Search component, and in ...