Skip to content

Commit 41821a9

Browse files
committed
chapter 3.1
1 parent becd9e6 commit 41821a9

File tree

3 files changed

+41
-5
lines changed

3 files changed

+41
-5
lines changed

package-lock.json

Lines changed: 27 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"version": "0.1.0",
44
"private": true,
55
"dependencies": {
6+
"axios": "^0.17.1",
67
"react": "^16.2.0",
78
"react-dom": "^16.2.0",
89
"react-scripts": "1.1.1"
@@ -13,4 +14,4 @@
1314
"test": "react-scripts test --env=jsdom",
1415
"eject": "react-scripts eject"
1516
}
16-
}
17+
}

src/App.js

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import React, { Component } from 'react';
2+
import axios from 'axios';
23
import './App.css';
34

45
const DEFAULT_QUERY = 'redux';
@@ -11,6 +12,8 @@ const PARAM_PAGE = 'page=';
1112
const PARAM_HPP = 'hitsPerPage=';
1213

1314
class App extends Component {
15+
_isMounted = false;
16+
1417
constructor(props) {
1518
super(props);
1619

@@ -55,18 +58,23 @@ class App extends Component {
5558
}
5659

5760
fetchSearchTopStories(searchTerm, page = 0) {
58-
fetch(`${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${searchTerm}&${PARAM_PAGE}${page}&${PARAM_HPP}${DEFAULT_HPP}`)
59-
.then(response => response.json())
60-
.then(result => this.setSearchTopStories(result))
61-
.catch(error => this.setState({ error }));
61+
axios(`${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${searchTerm}&${PARAM_PAGE}${page}&${PARAM_HPP}${DEFAULT_HPP}`)
62+
.then(result => this.setSearchTopStories(result.data))
63+
.catch(error => this._isMounted && this.setState({ error }));
6264
}
6365

6466
componentDidMount() {
67+
this._isMounted = true;
68+
6569
const { searchTerm } = this.state;
6670
this.setState({ searchKey: searchTerm });
6771
this.fetchSearchTopStories(searchTerm);
6872
}
6973

74+
componentWillUnmount() {
75+
this._isMounted = false;
76+
}
77+
7078
onSearchChange(event) {
7179
this.setState({ searchTerm: event.target.value });
7280
}

0 commit comments

Comments
 (0)