Last active
October 22, 2017 22:28
-
-
Save edulan/88cba5985dcc93618ed6544effe1c317 to your computer and use it in GitHub Desktop.
App component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class App extends PureComponent { | |
constructor (props) { | |
super(props) | |
this.state = { | |
term: props.term, | |
items: [], | |
errorMessage: null | |
} | |
this.performSearch = this.performSearch.bind(this) | |
this.receiveSearch = this.receiveSearch.bind(this) | |
this.setError = this.setError.bind(this) | |
this.setItems = this.setItems.bind(this) | |
this.setTerm = this.setTerm.bind(this) | |
} | |
componentDidMount () { | |
this.performSearch(this.state.term) | |
} | |
componentDidUpdate (_, prevState) { | |
const termChanged = prevState.term !== this.state.term | |
if (termChanged) { | |
this.performSearch(this.state.term) | |
} | |
} | |
performSearch (term) { | |
this.props.search(term).then(this.receiveSearch) | |
} | |
receiveSearch (search) { | |
if (search.error) { | |
this.setError(search.error.message) | |
return | |
} | |
this.setError(null) | |
this.setItems(search.result) | |
} | |
setError (errorMessage) { | |
this.setState(() => ({ errorMessage })) | |
} | |
setItems (items) { | |
this.setState(() => ({ items })) | |
} | |
setTerm (term) { | |
this.setState(() => ({ term })) | |
} | |
render () { | |
const { items, term, errorMessage } = this.state | |
return ( | |
<div className='App'> | |
<div className='Search'> | |
<Search | |
term={term} | |
onSearch={this.setTerm} | |
/> | |
</div> | |
<div className='Items'> | |
{errorMessage | |
? <Error message={errorMessage} /> | |
: <List items={items} />} | |
</div> | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment