Created
March 1, 2019 19:54
-
-
Save JFrankfurt/7024e17706ea15edc735d7755dfe4da6 to your computer and use it in GitHub Desktop.
Use an RXjs Subject to debounce text input
This file contains hidden or 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 { 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