Created
August 26, 2020 05:41
-
-
Save forsaken1/7ca241654117554adb7e1beafcc0d33e to your computer and use it in GitHub Desktop.
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
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