Skip to content

Instantly share code, notes, and snippets.

@forsaken1
Created August 26, 2020 05:41
Show Gist options
  • Save forsaken1/7ca241654117554adb7e1beafcc0d33e to your computer and use it in GitHub Desktop.
Save forsaken1/7ca241654117554adb7e1beafcc0d33e to your computer and use it in GitHub Desktop.
import React from 'react'
import { TextField, IconButton, CircularProgress } from '@material-ui/core'
import { CheckCircle } from '@material-ui/icons'
class AutoField extends React.Component {
constructor(props) {
super(props)
this.state = {
saving: false,
success: false,
value: ''
}
this.savingTimer = null
this.successTimer = null
}
componentWillUnmount() {
clearTimeout(this.savingTimer)
clearTimeout(this.successTimer)
}
componentDidMount() {
this.setState({value: this.props.value})
}
componentDidUpdate(props, _state, _snapshot) {
if(props.value !== this.props.value) {
this.setState({value: this.props.value, saving: false, success: false})
}
}
onChangeHandler = (e) => {
this.setState({value: e.target.value})
this.saving()
}
saving = () => {
if(this.savingTimer) {
clearTimeout(this.savingTimer)
}
this.savingTimer = setTimeout(_ => {
const { onChange } = this.props
const { value } = this.state
this.savingTimer = null
onChange(value)
this.setState({saving: true, success: false})
this.successTimer = setTimeout(_ => {
this.setState({saving: false, success: true})
setTimeout(_ => this.setState({success: false}), 3000)
}, 1000)
}, 500)
}
render() {
const { label } = this.props
const { value, saving, success } = this.state
return (
<div className="autofield">
<TextField label={label} variant="outlined" value={value} onChange={this.onChangeHandler} fullWidth/>
<div className="autofield-status">
{saving && <CircularProgress size={30}/>}
{success &&
<IconButton>
<CheckCircle style={{ color: 'green' }}/>
</IconButton>}
</div>
</div>
)
}
}
export default AutoField
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment