Skip to content

Commit

Permalink
fix(React Native): update <SearchBox> without Effects (#400)
Browse files Browse the repository at this point in the history
  • Loading branch information
francoischalifour authored Jul 7, 2022
1 parent e34bde4 commit 6bdbbab
Showing 1 changed file with 12 additions and 17 deletions.
29 changes: 12 additions & 17 deletions react-instantsearch-hooks-native/getting-started/src/SearchBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,35 +8,30 @@ type SearchBoxProps = UseSearchBoxProps & {

export function SearchBox({ onChange, ...props }: SearchBoxProps) {
const { query, refine } = useSearchBox(props);
const [value, setValue] = useState(query);
const [inputValue, setInputValue] = useState(query);
const inputRef = useRef<TextInput>(null);

// Track when the value coming from the React state changes to synchronize
// it with InstantSearch.
useEffect(() => {
if (query !== value) {
refine(value);
}
}, [value, refine]);
function setQuery(newQuery: string) {
setInputValue(newQuery);
refine(newQuery);
}

// Track when the InstantSearch query changes to synchronize it with
// the React state.
useEffect(() => {
// We bypass the state update if the input is focused to avoid concurrent
// updates when typing.
if (!inputRef.current?.isFocused() && query !== value) {
setValue(query);
}
}, [query]);
// We bypass the state update if the input is focused to avoid concurrent
// updates when typing.
if (query !== inputValue && !inputRef.current?.isFocused()) {
setInputValue(query);
}

return (
<View style={styles.container}>
<TextInput
ref={inputRef}
style={styles.input}
value={value}
value={inputValue}
onChangeText={(newValue) => {
setValue(newValue);
setQuery(newValue);
onChange(newValue);
}}
clearButtonMode="while-editing"
Expand Down

0 comments on commit 6bdbbab

Please sign in to comment.