user9917838
user9917838

Reputation: 18

How to gracefully close React Native Application for Android

I am new to React Native Application. I am using below code to close the application on clicking of a button.

BackHandler.exitApp();
return false;

But application is not properly ended and still is in Taskbar. So when I try to open the application again, componentWillMount never executes.

I am using below version of React Native.

Any help or advice on how to cleanly close React Native Application?

Thanks in advance.

Upvotes: 0

Views: 1496

Answers (1)

bennygenel
bennygenel

Reputation: 24670

Google and Apple won't advice to force quit an application so you should avoid doing that so for better user experience.

If you need to recall a function when your app comes back from background you can use react-native's Appstate API. With Appstate you can listen for app states (active, background and inactive) and run your desired function.

AppState can tell you if the app is in the foreground or background, and notify you when the state changes.

Below is a sample for requesting data and refreshing the list on every time screen comes back foreground.

Sample

import React, { Component } from 'react';
import { Text, View, FlatList, StyleSheet, AppState } from 'react-native';

export default class App extends Component {
  state = {
    data: []
  }
  requestItems = () => {
    fetch('someurl').then((response) => response.json()).then((responseJSON) => this.setState({data: responseJSON.data}))
  }
  componentDidMount() {
    this.requestItems()
    AppState.addEventListener('change', this.requestItems);
  }
  componentWillUnmount() {
     AppState.removeEventListener('change', this.requestItems);
  }
  renderItem = ({item}) => <Text>{item.text}</Text>
  render() {
    if (this.state.data.lenght === 0) return <Text>{'Loading'}</Text>
    return (
      <View style={styles.container}>
        <FlatList data={this.state.data} renderItem={this.renderItem} keyExtractor={(item) => item.id} />
      </View>
    );
  }
}  

Upvotes: 2

Related Questions