Skip to content

Commit 62c8ed5

Browse files
committed
Revisited: setState() (End 6 chapter)
1 parent 8209a2f commit 62c8ed5

File tree

2 files changed

+23
-19
lines changed

2 files changed

+23
-19
lines changed

src/App.js

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,27 @@ const SORTS = {
3333
POINTS: list => sortBy(list, 'points').reverse(),
3434
};
3535

36+
const updateSearchTopStoriesState = (hits, page) => (prevState) => {
37+
const { searchKey, results } = prevState;
38+
39+
const oldHits = results && results[searchKey]
40+
? results[searchKey].hits
41+
: [];
42+
43+
const updatedHits = [
44+
...oldHits,
45+
...hits
46+
];
47+
48+
return {
49+
results: {
50+
...results,
51+
[searchKey]: { hits: updatedHits, page }
52+
},
53+
isLoading: false
54+
};
55+
};
56+
3657
class App extends Component {
3758
constructor(props) {
3859
super(props);
@@ -59,24 +80,7 @@ class App extends Component {
5980

6081
setSearchTopStories(result) {
6182
const { hits, page } = result;
62-
const { searchKey, results } = this.state;
63-
64-
const oldHits = results && results[searchKey]
65-
? results[searchKey].hits
66-
: [];
67-
68-
const updatedHits = [
69-
...oldHits,
70-
...hits
71-
];
72-
73-
this.setState({
74-
results: {
75-
...results,
76-
[searchKey]: { hits: updatedHits, page }
77-
},
78-
isLoading: false
79-
});
83+
this.setState(updateSearchTopStoriesState(hits, page));
8084
}
8185

8286
fetchSearchTopStories(searchTerm, page = 0) {

src/__snapshots__/App.test.js.snap

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ exports[`Table has a valid snapshot 1`] = `
146146
}
147147
>
148148
<button
149-
className="button-inline button-active"
149+
className="button-inline"
150150
onClick={[Function]}
151151
type="button"
152152
>

0 commit comments

Comments
 (0)