Created
April 27, 2017 20:21
-
-
Save AlexFrazer/3866ad231c054a76972ed1e41506f2a7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import React, { Component } from 'react'; | |
type Props = { | |
value: ?string, | |
onChange: ?() => {}, | |
onStopTyping: ?() => void, | |
onStartTyping: ?() => void, | |
}; | |
type State = { | |
isTyping: boolean, | |
}; | |
export default class ChatInput extends Component { | |
props: Props; | |
static defaultProps = { | |
value: '', | |
onChange: () => {}, | |
onStopTyping: () => {}, | |
onStartTyping: () => {}, | |
}; | |
state: State = { | |
isTyping: false, | |
}; | |
componentDidUpdate(props, { isTyping: wasTyping }) { | |
if (wasTyping !== this.state.isTyping) { | |
this.state.isTyping ? this.props.onStartTyping() : this.props.onStopTyping(); | |
} | |
} | |
timerId = null; | |
wait(ms: number) { | |
return new Promise(resolve => { | |
this.timerId = setTimeout(resolve, ms); | |
}).finally(() => { | |
this.timerId = clearTimeout(this.timerId); | |
}); | |
} | |
onKeyDown = e => { | |
clearTimeout(this.timerId); | |
this.setState({ isTyping: true }); | |
}; | |
onKeyUp = async e => { | |
await this.wait(3000); | |
this.setState({ isTyping: false }); | |
}; | |
render() { | |
const { value } = this.props; | |
return ( | |
<div> | |
<Input | |
value={value} | |
onKeyUp={this.onKeyUp} | |
onKeyDown={this.onKeyDown} | |
onChange={({ target: { value } }) => onChange(value)} | |
/> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment