Skip to content
This repository was archived by the owner on Mar 6, 2025. It is now read-only.

Commit 5722149

Browse files
matijsImreBognarUltimaker
authored andcommitted
Allow parent components to reset SearchBar's query
A SearchBar is responsible for its own internal state and rendering once it's mounted. This change allows a parent component to force SearchBar to update its internal state (the value of query) to a new value.
1 parent 2b76faf commit 5722149

2 files changed

Lines changed: 15 additions & 4 deletions

File tree

src/components/search_bar/__tests__/__snapshots__/search_bar.test.tsx.snap

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ exports[`search_bar.tsx snapshot and instance 1`] = `
55
emitDelay={0}
66
onChange={[MockFunction]}
77
placeholder="For example…"
8+
query=""
89
>
910
<div
1011
className="search-bar"

src/components/search_bar/search_bar.tsx

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ interface SearchBarState {
1818
class SearchBar extends React.Component<SearchBarProps, SearchBarState> {
1919
static defaultProps = {
2020
emitDelay: 0,
21+
query: '',
2122
}
2223

2324
debouncedEmit = (({ onChange, emitDelay }) => debounce(
@@ -26,7 +27,7 @@ class SearchBar extends React.Component<SearchBarProps, SearchBarState> {
2627

2728
constructor(props: Readonly<SearchBarProps>) {
2829
super(props);
29-
const { query = '' } = props;
30+
const { query } = props;
3031
this.state = {
3132
query,
3233
};
@@ -40,18 +41,27 @@ class SearchBar extends React.Component<SearchBarProps, SearchBarState> {
4041
}
4142
}
4243

44+
componentDidUpdate(prevProps: SearchBarProps, prevState: SearchBarState) {
45+
const { query } = this.props;
46+
if (query !== prevProps.query && query !== prevState.query) {
47+
// eslint-disable-next-line react/no-did-update-set-state
48+
this.setState({
49+
query,
50+
});
51+
}
52+
}
53+
4354
componentWillUnmount() {
4455
this.debouncedEmit.cancel();
4556
}
4657

4758
onChange(event: React.ChangeEvent<HTMLInputElement>) {
4859
const { value: query } = event.target;
49-
5060
this.setState({
5161
query,
62+
}, () => {
63+
this.debouncedEmit(query);
5264
});
53-
event.persist();
54-
this.debouncedEmit(query);
5565
}
5666

5767
render() {

0 commit comments

Comments
 (0)