Skip to content

Instantly share code, notes, and snippets.

@n9iels
Created Jul 31, 2018
Embed
What would you like to do?
A simple loop to save content while editing without race conditions
import * as React from 'react'
type SampleComponentProps = {
value: string
save: (value: string, callback: () => void) => void
}
type SampleComponentState = {
value: string
status: 'dirty' | 'waiting'
}
export class SampleComponent extends React.Component<SampleComponentProps, SampleComponentState> {
private editor: HTMLElement
private running: boolean = false
constructor(props: SampleComponentProps) {
super(props)
this.state = { value: props.value, status: 'waiting' }
}
componentDidMount() {
if (this.running) return
this.running = true
var self = this
let process = () => setTimeout(() => {
if (self.state.status == 'dirty') {
if (!self.running) return
this.setState(
prevState => ({ ...prevState, status: 'waiting' }),
() => this.props.save(this.state.value, () => process())
)
} else {
if (self.running) {
process()
}
}
}, 500)
process()
}
componentWillUnmount() {
this.running = false
}
render() {
return <textarea onChange={e => this.setState(prevState => ({ ...prevState, value: e.currentTarget.value, status: 'dirty' }))}>{this.state.value}</textarea>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment