Mohamadamin
Mohamadamin

Reputation: 607

How to reload react-native-webview content on appState change

I have a webview in my app. I set onNavigationStateChange props for it to handle click on any link on webview and navigate user to browser. The issue is when the user press BackAndroid on browser on come back in my app webview content not showing and screen is empty and white. For this issue I try to use appState and handle its changes to reload webview after coming back in my app, but got this error enter image description here

Here is my code:

function Screen(props) {
  const [appState, setAppState] = React.useState(AppState.currentState);
  let webview = React.useRef(null);
  React.useEffect(() => {
    AppState.addEventListener('change', handleAppStateChange);
    return () => AppState.removeEventListener('change', handleAppStateChange);
  }, []);
  function backHandler() {
    popScreen(Screens.About);
    return true;
  }
  function handleAppStateChange(nextAppState) {
    if (nextAppState === 'active') {
      webview.reload();
    }
    setAppState(nextAppState);
  }
  const WebView = require('react-native-webview').default;
  return (
      <View style={styles.container}>
        <View style={styles.web}>
          <WebView
            ref={ref => {
              webview = ref;
            }}
            source={{uri: props.link}}
            androidHardwareAccelerationDisabled={true} // for prevent crash
            startInLoadingState={true}
            onNavigationStateChange={event => {
              if (event.url !== props.link) {
                webview.stopLoading();
                Linking.openURL(event.url);
              }
            }}
            renderLoading={() => (
              <CircleLoading
                containerStyle={[styles.loading]}
                renderLoading={true}
              />
            )}
          />
        </View>
      </View>
  );
}

Thanks.

Upvotes: 0

Views: 2234

Answers (1)

D10S
D10S

Reputation: 1549

try it this way:

const [appState, setAppState] = React.useState(AppState.currentState);
  const webview = React.useRef(null);
  React.useEffect(() => {
    AppState.addEventListener('change', handleAppStateChange);
    return () => AppState.removeEventListener('change', handleAppStateChange);
  }, [webview.current]);//    <---- CHANGED
  function backHandler() {
    popScreen(Screens.About);
    return true;
  }
  function handleAppStateChange(nextAppState) {
    if (nextAppState === 'active') {
      webview.current.reload(); //     <---- CHANGED
    }
    setAppState(nextAppState);
  }
  const WebView = require('react-native-webview').default; //  <---- remove it and import it at top of file
  return (
      <View style={styles.container}>
        <View style={styles.web}>
          <WebView
            ref={webview} //    <---- CHANGED
            ..

Upvotes: 1

Related Questions