Skip to content

Instantly share code, notes, and snippets.

@JFrankfurt
Created March 1, 2019 19:54
Show Gist options
  • Save JFrankfurt/7024e17706ea15edc735d7755dfe4da6 to your computer and use it in GitHub Desktop.
Save JFrankfurt/7024e17706ea15edc735d7755dfe4da6 to your computer and use it in GitHub Desktop.
Use an RXjs Subject to debounce text input
import { Subject } from 'rxjs'
import { debounceTime } from 'rxjs/operators'
const simpleTextFilter = filterString => (object = {}) => {
return typeof filterString === 'string'
? Object.values(object)
.toString()
.toLowerCase()
.includes(filterString.toLowerCase())
: false
}
class UserIndexScreen extends Component {
state = {
filterString: '',
}
searchText$ = new Subject()
componentDidMount() {
this.subscription = this.searchText$
.pipe(debounceTime(250))
.subscribe(filterString => this.setState({ filterString }))
}
componentWillUnmount() {
this.subscription.unsubscribe()
}
handleKey = ({ target }) => this.searchText$.next(target.value)
render() {
const { handleKey } = this
const { filterString } = this.state
const { registry, users_fetching: usersFetching } = this.props.users
const { user } = this.props.user
const filterFunc = simpleTextFilter(filterString)
let content
if (usersFetching) {
content = <Spinner />
} else {
const UserRows = Object.values(registry)
.filter(filterFunc)
.map(usr => <UserRow user={usr} userRole={user.role} />)
content = (
<>
<TextField
style={{ marginBottom: 8 }}
placeholder="Search"
onChange={handleKey}
/>
<Table>
<th>{UserHeading}</th>
<tb>{UserRows}</tb>
</Table>
</>
)
}
return (
<div>
<h1>All Users</Header>
<div className={css(layoutStyles.content)}>{content}</div>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment