Skip to content

Commit

Permalink
SmartUrlInput: Use useFocusEffect.
Browse files Browse the repository at this point in the history
Following the doc at
  https://reactnavigation.org/docs/use-focus-effect/.

Greg points out [1] that `useFocusEffect` seems to have the effect
of calling the callback even on the component's first mount (if the
screen is focused), whereas the old listener-based code would not.
That doesn't seem to have a practical effect, here; empirically, it
looks like the input gets focused anyway before this change. That's
probably due to the `autoFocus` prop we pass to the `TextInput`.

[1] zulip#4914 (comment).
  • Loading branch information
chrisbobbe committed Jul 27, 2021
1 parent 22c6fba commit 6b7f5f5
Showing 1 changed file with 6 additions and 14 deletions.
20 changes: 6 additions & 14 deletions src/common/SmartUrlInput.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* @flow strict-local */
import React, { useState, useRef, useCallback, useContext, useEffect } from 'react';
import React, { useState, useRef, useCallback, useContext } from 'react';
import { TextInput, TouchableWithoutFeedback, View } from 'react-native';
import { useFocusEffect } from '@react-navigation/native';
import type { ViewStyleProp } from 'react-native/Libraries/StyleSheet/StyleSheet';

import type { AppNavigationProp } from '../nav/AppNavigator';
Expand Down Expand Up @@ -62,7 +63,6 @@ export default function SmartUrlInput(props: Props) {
onChangeText,
onSubmitEditing,
enablesReturnKeyAutomatically,
navigation,
} = props;

// We should replace the fixme with
Expand All @@ -71,8 +71,6 @@ export default function SmartUrlInput(props: Props) {
// this is probably down to bugs in Flow's special support for React.
const textInputRef = useRef<$FlowFixMe>();

const unsubscribeFocusListener = useRef<(() => void) | void>(undefined);

/**
* The actual input string, exactly as entered by the user,
* without modifications by autocomplete.
Expand All @@ -81,20 +79,14 @@ export default function SmartUrlInput(props: Props) {

const themeContext = useContext(ThemeContext);

const { addListener } = navigation;
useEffect(() => {
unsubscribeFocusListener.current = addListener('focus', () => {
useFocusEffect(
useCallback(() => {
if (textInputRef.current) {
// `.current` is not type-checked; see definition.
textInputRef.current.focus();
}
});
return () => {
if (unsubscribeFocusListener.current) {
unsubscribeFocusListener.current();
}
};
}, [addListener]);
}, []),
);

const handleChange = useCallback(
(_value: string) => {
Expand Down

0 comments on commit 6b7f5f5

Please sign in to comment.