1
1
import React , { Component } from 'react' ;
2
+ import axios from 'axios' ;
2
3
import './App.css' ;
3
4
4
5
const DEFAULT_QUERY = 'redux' ;
@@ -11,6 +12,8 @@ const PARAM_PAGE = 'page=';
11
12
const PARAM_HPP = 'hitsPerPage=' ;
12
13
13
14
class App extends Component {
15
+ _isMounted = false ;
16
+
14
17
constructor ( props ) {
15
18
super ( props ) ;
16
19
@@ -55,18 +58,23 @@ class App extends Component {
55
58
}
56
59
57
60
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 } ) ) ;
62
64
}
63
65
64
66
componentDidMount ( ) {
67
+ this . _isMounted = true ;
68
+
65
69
const { searchTerm } = this . state ;
66
70
this . setState ( { searchKey : searchTerm } ) ;
67
71
this . fetchSearchTopStories ( searchTerm ) ;
68
72
}
69
73
74
+ componentWillUnmount ( ) {
75
+ this . _isMounted = false ;
76
+ }
77
+
70
78
onSearchChange ( event ) {
71
79
this . setState ( { searchTerm : event . target . value } ) ;
72
80
}
0 commit comments