Update state when user press back button in React Native

press back again to exit react native
how to use backhandler react native
react native-navigation override back button
react native webview back button
back press subscriptions(i is not a function)
backhandler not working react native
how to disable back button in react native
react native ios back button

I use react-navigation for manage routes. This is my Home component:

class HomeScreen extends React.Component {
   constructor(props) {
      this.state = {
         userProfile: {
            firstname: 'John',
            avatar: 'john-profile.png',
            location: 'Canada',
         }
      }
   }

   componentDidMount() {
      AsyncStorage.getItem('userProfile', (errs, result) => {
         this.setState({userProfile: JSON.parse(result)});
      });
   }

   render() {
      return (
         <View>
            <Image src="{this.state.userProfile.avatar}" />
            <Text>Firstname: {this.state.userProfile.firstname}</Text>
            <Text>Location: {this.state.userProfile.location}</Text>
         </View>
      );
   }
}

And this is the Profile screen:

class ProfileScreen extends React.Component {
   constructor(props) {
      this.state = {
         userProfile: null,
      }
   }

   componentDidMount() {
      AsyncStorage.getItem('userProfile', (errs, result) => {
         this.setState({userProfile: JSON.parse(result)});
      });
   }

   save() {

      var userSavedProfile = this.state.userProfile;

      userSavedProfile.firstname = "Peter";
      userSavedProfile.avatar = "peter-avatar.png";
      userSavedProfile.location = "EEUU";

      this.setState({userProfile: userSavedProfile});

      AsyncStorage.setItem('userProfile',     JSON.stringify(this.state.userProfile), () => {});

   }

   render() {
      return (
         <View>
            <Button title="Save" onPress={() => this.save()}  />
         </View>
      );
   }
}

When I save the new user information and I press back button in header (react-navigation) the user profile is old, firstname = John, etc... How update state from Home when user press back button and refresh data?

You can use BackHandler from react-native https://facebook.github.io/react-native/docs/backhandler.html You can change state inside function of backhandler

React Native - Device back button handling, How do you handle the back button in react native? September 6, 2019August 7, 2018. When the user presses the Android hardware back button in React Native, react-navigation will pop a screen or exit the app if there are no screens to pop. This is the sensible default behavior, but there are situations when you might want to implement custom handling.

I think that your application would need a state manager, where you could store your user information and access it anywhere in the app. You should take a look at Redux. It would fit your needs and the info in your Home screen would automatically update.

State Management in React Native, press when having only one screen to exit the app requires a custom setting. React Native Override Android Hardware Back Button Behavior In this example we are going to implement android hardware back button press event listener in react native application. Go through the below steps that help you to build more understanding on this.

but for anyone who will need this functionality in there react native application here is the solution you can try. using react navigation.

import {withNavigationFocus} from "react-navigation";
class Profile extends Component {
    ...
}
export default withNavigationFocus(Profile);

Preventing hardware back button android for React Native, How do I disable the Back button in react native? A basic button component that should render nicely on any platform. Supports a minimal level of customization. If this button doesn't look right for your app, you can build your own button using TouchableOpacity or TouchableNativeFeedback. For inspiration, look at the source code for this button component.

There can be two workarounds check it out -

1 Send callback in params

class HomeScreen extends React.Component {
   constructor(props) {
      this.state = {
         userProfile: {
            firstname: 'John',
            avatar: 'john-profile.png',
            location: 'Canada',
         }
      }

      this.getUserData = this.getUserData.bind(this);
   }

   componentDidMount() {
       this.getUserData;
   }

   getUserData = () =>{
         AsyncStorage.getItem('userProfile', (errs, result) => {
            this.setState({userProfile: JSON.parse(result)});
         });
    }

   render() {
      return (
         <View>
            <Image src="{this.state.userProfile.avatar}" />
            <Text onPress={()=>this.props.navigation.navigate('ProfileScreen', this.getUserData)}>Firstname: {this.state.userProfile.firstname}</Text>
            <Text>Location: {this.state.userProfile.location}</Text>
         </View>
      );
   }
}
class ProfileScreen extends React.Component {
   constructor(props) {
      this.state = {
         userProfile: null,
      }
   }

   componentDidMount() {
      AsyncStorage.getItem('userProfile', (errs, result) => {
         this.setState({userProfile: JSON.parse(result)});
      });
   }

   save() {

      var userSavedProfile = this.state.userProfile;

      userSavedProfile.firstname = "Peter";
      userSavedProfile.avatar = "peter-avatar.png";
      userSavedProfile.location = "EEUU";

      this.setState({userProfile: userSavedProfile});

      AsyncStorage.setItem('userProfile',     JSON.stringify(this.state.userProfile), () => {});

      //this is the magic
      this.props.navigation.state.params.getUserData();

   }

   render() {
      return (
         <View>
            <Button title="Save" onPress={() => this.save()}  />
         </View>
      );
   }
}

2 On HomeScreen Constructor add this (Dirty one)

this.props.navigation.addListener(
      'didFocus',
      payload => {
        this.setState({is_updated:true});
      }
);

How to get the current screen metadata in React within react , Android Back Button handling in React Native apps — 1x08 2. if there is no previous view to navigate to (i.e user in Home view), it should prompt the user with React native provides BackHandler API (there's also BackAndroid but it's deprecated) for detecting hardware back button presses. super(props); this.​state = {}; }  To finalize installation of react-native-gesture-handler, add the following at the top (make sure it's at the top and there's nothing else before it) of your entry file, such as index.js or App.js: import 'react-native-gesture-handler'; Now, you need to wrap the whole app in NavigationContainer.

You can use componentDidUpdate(){...} insted componentDidMount(){}

Android Back Button handling in React Native apps, As an Android user moves through your app and goes deeper and deeper into The default React Native behavior for the back button is that pressing the We will use React Side Effect to update the function that is called  Another common interaction is the press and hold to fire an action. Sometimes it's delete, sometimes it's save, but whatever it is you want to provide feedback to your user. React Native ships with a few Touchable components like TouchableOpacity , TouchableHighlight and also TouchableBounce that provide feedback to users but we'll build a

Handling Android Back Button Events in React Native with Custom , The Backhandler API detects hardware button presses for back navigation, lets you register Typically you would use the navigator here to go to the last state. State works the same way as it does in React, so for more details on handling state, you can look at the React.Component API. At this point, you may have noticed that most of our examples use the default text color. To customize the text color, you will have to learn about Style.

BackHandler · React Native, transitions. Using the `BackHandler` from React Native we can ask the screen if custom needs are required when the hardware back button is pressed. Finally we'll prompt the user if they want to navigate. into your app. Not only that you may want to control the back navigation based upon the state of your application. On Android, React Navigation hooks in to the hardware back button and fires the goBack() function for you when the user presses it, so it behaves as the user would expect. Another common requirement is to be able to go back multiple screens -- for example, if you are several screens deep in a stack and want to dismiss all of them to go back to the first screen.

Custom Handling the Android Back Button with React Navigation, When the user presses the Android hardware back button in React Native, react-​navigation will pop a screen or exit the app if there are no screens to pop. The default React Native behavior for the back button is that pressing the button will exit the app. React Native provides a BackAndroid module that gives developers control of back button behavior. This module is in charge of registering callbacks to decide what to do when the back button is pressed.

Comments
  • I was also facing the same issue but I resolved it. Can you please tell me, how are you moving to profile screen? Is home is a parent class for profile screen ?
  • please let me know then I will post my code here.
  • But backhandler is used in this case on ProfileScreen for back to HomeScreen. In the documentation I see not apply for iOs devices. I need refresh state in Home when user press back button from ProfileScreen.
  • From what I understood you want to up date state in HomeScreen from an action in ProfileScreen for this declare a function in Home Screen like getData() write all your logic in HomeScreen getData and then send it as props to ProfileScreen and call the function in onPress of the button