Skip to content

Instantly share code, notes, and snippets.

@AlexFrazer
Created April 27, 2017 20:21
Show Gist options
  • Save AlexFrazer/3866ad231c054a76972ed1e41506f2a7 to your computer and use it in GitHub Desktop.
Save AlexFrazer/3866ad231c054a76972ed1e41506f2a7 to your computer and use it in GitHub Desktop.
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