react-native-camera barcode scanner freezes, because it scans too fast - react-native

I am trying to use the barcode scanner from react-native-camera. First, off it scans a QR-code and extracts a String, after that it navigates to the next Screen with react-navigation. In the second screen, it makes an API-call.
Now if I go back to the scanner screen, de QR-code will be scanned immediately. That's where I run into an error and the scanner freezes. I usually get this error:
Can't call setState (or forceUpdate) on an unmounted component
I think it's because my componentWillUnmount cleanup doesn't work properly or fast enough, but I already cancel the axios request.
requestCode = (code) => {
if (cancel != undefined) {
cancel();
}
axios.get(API_URI + code, {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
})
}).then(response => {
console.log(response)
//checks if code was already called
this.checkUsed(response.data)
})
.catch(error => {
this.setState({ isValid: false })
});
}
componentWillUnmount() {
cancel();
}
Maybe I could mount the camera-scanner a little bit later so it doesn't scan this fast or is it maybe even an error with React Navigation?

You can use a flag to control.
class QR extends Component {
constructor(props) {
super(props)
this.state = {
scanable: true
}
this.cameraAttrs = {
ref: ref => {
this.camera = ref
},
style: styles.preview,
type: RNCamera.Constants.Type.back,
barCodeTypes: [RNCamera.Constants.BarCodeType.qr],
onBarCodeRead: ({ data }) => {
this.callback(data)
}
}
}
componentWillMount() {
this._mounted = true
}
componentWillUnmount() {
this._mounted = false
}
callback(text) {
if (!this.state.scanable) {
return
}
console.log(text)
this.setState({ scanable: false })
setTimeout(() => {
if (this._mounted) {
this.setState({ scanable: true })
}
}, 1000) // 1s cooldown
}
render() {
return (
<View style={styles.container}>
<RNCamera
{...this.cameraAttrs}
>
</RNCamera>
</View>
)
}
}

Related

react native setInterval cannot read property apply

I am new in react native I am trying to render the count of unread notification for that I called my API in HOC it is working fine for initial few seconds but after that, I started to get the below error
func.apply is not a function
below is my code
import React, { Component } from "react";
import PropTypes from "prop-types";
import { Modal, View } from "react-native";
import { themes } from "./constants";
import { AsyncStorage } from "react-native";
export default (OriginalComponent, animationType) =>
class extends Component {
static propTypes = {
handleFail: PropTypes.func,
theme: PropTypes.string,
visible: PropTypes.bool
};
state = {
modalVisible: true
};
static getDerivedStateFromProps({ visible }) {
if (typeof visible === "undefined") {
setInterval(
AsyncStorage.getItem("loginJWT").then(result => {
if (result !== null) {
result = JSON.parse(result);
fetch(serverUrl + "/api/getUnreadNotificationsCount", {
method: "GET",
headers: {
Authorization: "Bearer " + result.data.jwt
}
})
.then(e => e.json())
.then(function(response) {
if (response.status === "1") {
if (response.msg > 0) {
AsyncStorage.setItem(
"unreadNotification",
JSON.stringify(response.msg)
);
} else {
AsyncStorage.setItem("unreadNotification", 0);
}
}
})
.catch(error => {
alert(error);
// console.error(error, "ERRRRRORRR");
});
} else {
AsyncStorage.setItem("unreadNotification", 0);
}
}),
5000
);
return null;
}
return { modalVisible: visible };
}
handleOpenModal = () => {
this.setState({ modalVisible: true });
};
handleCloseModal = () => {
const { handleFail } = this.props;
this.setState({ modalVisible: false }, handleFail);
};
render() {
const { modalVisible } = this.state;
const { theme } = this.props;
return (
<View>
<Modal
animationType={animationType ? animationType : "fade"}
transparent={true}
visible={modalVisible}
onRequestClose={this.handleCloseModal}
>
<View style={themes[theme] ? themes[theme] : themes.transparent}>
<OriginalComponent
handleCloseModal={this.handleCloseModal}
{...this.props}
/>
</View>
</Modal>
</View>
);
}
};
I have not used getDerivedStateFromProps but, according to the docs, it is called on initial component mount and before each render update.
Thus your code is creating a new interval timer on each update without clearing any of the earlier timers, which could be causing a race condition of some sort.
You may want to consider using the simpler alternatives listed in the docs, or at a minimum, insure that you cancel an interval before creating a new one.

'Warning: Can\'t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application

im building a react native application ,still i have 2 screens
1.Enter mobile
2.Verify Otp
EnterUserInfo.js
class UserInfoInput extends Component {
constructor(props) {
super(props);
this.state = { formValid:true,
validMobileNumber:false,
.
.}}
componentWillReceiveProps(nextProps) {
if(nextProps.common.isFetching===false) {
this.props.navigation.navigate('VerifyOtpScreen')
.
.
} else {
this.setState({isLoading:true})
}}
onPressNext=()=> {
this.props.sendOtp(payload)}
render() {
return (<View/>)
}
}
}
function mapStateToProps(state) {
return {
common: state.common
}
}
function mapDispatchToProps(dispatch) {
return {
...bindActionCreators({ sendOtp }, dispatch)
}
}
export default connect(mapStateToProps,mapDispatchToProps)(UserInfoInput);
Here user enter the phone number ,and trigger an action sendOtp,response will be in the reducer and it will be available in the componentwillrecieveprops() lifecycle.
VerifyOtp.js
class VerifyOtp extends Component {
constructor(props) {
super(props);
this.state = { oneTimePIN: '' ,
.};
}
componentDidMount(){
this.setState({ phoneNumber:this.props.common.phone});
}
componentWillMount() {
setTimeout(() => {
this.setState({ isResendDisabled: false, opacity: 1 });
}, 30000);
}
componentWillReceiveProps(nextProps){
//do operation
}
onPressNext=()=>{
if(this.state.oneTimePIN=='') {
this.setState({showNotification:true})
}
else {
this.onSubmit()
}
}
onSubmit=()=>{
this.props.verifyOtp(payload)
}
onResendOtp=()=>{
this.props.sendOtp(payload,locationData)
this.setState({ isResendDisabled: true, opacity: 0.5 });
setTimeout(() => {
this.setState({ isResendDisabled: false, opacity: 1 });
}, 30000);
}
render() {
return (<View><Elements></View>)
}
}
function mapStateToProps(state) {
return {
common: state.common
}
}
function mapDispatchToProps(dispatch) {
return {
...bindActionCreators({ verifyOtp,sendOtp }, dispatch)
}
}
export default connect(mapStateToProps,mapDispatchToProps)(VerifyOtp);
VerifyOtp screen used to verify the otp.
The problem is,If i move back to enterUserinfo screen and move again to the verifyOtp screen im getting the warning message
'Warning: Can\'t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application
What is the reason for the warning , and how tackle the issue?
This happens when you call an async function followed by setstate.
A simple work around would be like this:
constructor(props) {
this.state = {
...
this.isCancelled: false
}
}
componentWillMount() {
setTimeout(() => {
!this.state.isCancelled && this.setState({ isResendDisabled: false,
opacity: 1 });
}, 30000);
}
and in componentWillUnmount
componentWillUnmount() {
// setting it true to avoid setState waring since componentWillMount is async
this.state.isCancelled = true;
}

React Native Flat List doesn't call onEndReached handler after two successful calls

I implement a very simple list that calls a server that returns a page containing books.Each book has a title, author, id, numberOfPages, and price). I use a Flat List in order to have infinite scrolling and it does its job very well two times in a row (it loads the first three pages) but later it doesn't trigger the handler anymore.
Initially it worked very well by fetching all available pages, but it stopped working properly after I added that extra check in local storage. If a page is available in local storage and it has been there no longer than 5 seconds I don't fetch the data from the server, instead I use the page that is cached. Of course, if there is no available page or it is too old I fetch it from the server and after I save it in local storage.(Something went wrong after adding this behavior related to local storage.)
Here is my component:
export class BooksList extends Component {
constructor(props) {
super(props);
this.state = {
pageNumber: 0
};
}
async storePage(page, currentTime) {
try {
page.currentTime = currentTime;
await AsyncStorage.setItem(`page${page.page}`, JSON.stringify(page));
} catch (error) {
console.log(error);
}
}
subscribeToStore = () => {
const { store } = this.props;
this.unsubsribe = store.subscribe(() => {
try {
const { isLoading, page, issue } = store.getState().books;
if (!issue && !isLoading && page) {
this.setState({
isLoading,
books: (this.state.books ?
this.state.books.concat(page.content) :
page.content),
issue
}, () => this.storePage(page, new Date()));
}
} catch (error) {
console.log(error);
}
});
}
componentDidMount() {
this.subscribeToStore();
// this.getBooks();
this.loadNextPage();
}
componentWillUnmount() {
this.unsubsribe();
}
loadNextPage = () => {
this.setState({ pageNumber: this.state.pageNumber + 1 },
async () => {
let localPage = await AsyncStorage.getItem(`page${this.state.pageNumber}`);
let pageParsed = JSON.parse(localPage);
if (localPage && (new Date().getTime() - localPage.currentTime) < 5000) {
this.setState({
books: (
this.state.books ?
this.state.books.concat(pageParsed.content) :
page.content),
isLoading: false,
issue: null
});
} else {
const { token, store } = this.props;
store.dispatch(fetchBooks(token, this.state.pageNumber));
}
});
}
render() {
const { isLoading, issue, books } = this.state;
return (
<View style={{ flex: 1 }}>
<ActivityIndicator animating={isLoading} size='large' />
{issue && <Text>issue</Text>}
{books && <FlatList
data={books}
keyExtractor={book => book.id.toString()}
renderItem={this.renderItem}
renderItem={({ item }) => (
<BookView key={item.id} title={item.title} author={item.author}
pagesNumber={item.pagesNumber} />
)}
onEndReachedThreshold={0}
onEndReached={this.loadNextPage}
/>}
</View>
)
}
}
In the beginning the pageNumber available in the state of the component is 0, so the first time when I load the first page from the server it will be incremented before the rest call.
And here is the action fetchBooks(token, pageNumber):
export const fetchBooks = (token, pageNumber) => dispatch => {
dispatch({ type: LOAD_STARTED });
fetch(`${httpApiUrl}/books?pageNumber=${pageNumber}`, {
headers: {
'Authorization': token
}
})
.then(page => page.json())
.then(pageJson => dispatch({ type: LOAD_SUCCEDED, payload: pageJson }))
.catch(issue => dispatch({ type: LOAD_FAILED, issue }));
}
Thank you!

this.setState inside Promise cause strange behavior

Simplified issue. Calling this.setState inside a Promise, renders before ends pending Promise.
My problems are:
The this.setState is not immediatly returned
I expected it to be async, so that the pending promise will be closed first.
If something will break inside the render function, the catch inside the Promise is called.
Maybe same issue as 1) that it seems like the render is still in context of the promise in which the this.setState was called.
import dummydata_rankrequests from "../dummydata/rankrequests";
class RankRequestList extends Component {
constructor(props) {
super(props);
this.state = { loading: false, data: [], error: null };
this.makeRankRequestCall = this.makeRankRequestCall.bind(this);
this.renderItem = this.renderItem.bind(this);
}
componentDidMount() {
// WORKS AS EXPECTED
// console.log('START set');
// this.setState({ data: dummydata_rankrequests.data, loading: false });
// console.log('END set');
this.makeRankRequestCall()
.then(done => {
// NEVER HERE
console.log("done");
});
}
makeRankRequestCall() {
console.log('call makeRankRequestCall');
try {
return new Promise((resolve, reject) => {
resolve(dummydata_rankrequests);
})
.then(rankrequests => {
console.log('START makeRankRequestCall-rankrequests', rankrequests);
this.setState({ data: rankrequests.data, loading: false });
console.log('END _makeRankRequestCall-rankrequests');
return null;
})
.catch(error => {
console.log('_makeRankRequestCall-promisecatch', error);
this.setState({ error: RRError.getRRError(error), loading: false });
});
} catch (error) {
console.log('_makeRankRequestCall-catch', error);
this.setState({ error: RRError.getRRError(error), loading: false });
}
}
renderItem(data) {
const height = 200;
// Force a Unknown named module error here
return (
<View style={[styles.item, {height: height}]}>
</View>
);
}
render() {
let data = [];
if (this.state.data && this.state.data.length > 0) {
data = this.state.data.map(rr => {
return Object.assign({}, rr);
});
}
console.log('render-data', data);
return (
<View style={styles.container}>
<FlatList style={styles.listContainer1}
data={data}
renderItem={this.renderItem}
/>
</View>
);
}
}
Currrent logs shows:
render-data, []
START makeRankRequestCall-rankrequests
render-data, [...]
_makeRankRequestCall-promisecatch Error: Unknown named module...
render-data, [...]
Possible Unhandled Promise
Android Emulator
"react": "16.0.0-alpha.12",
"react-native": "0.46.4",
EDIT:
wrapping setTimeout around this.setState also works
setTimeout(() => {
this.setState({ data: respData.data, loading: false });
}, 1000);
EDIT2:
created a bug report in react-native github in parallel
https://github.com/facebook/react-native/issues/15214
Both Promise and this.setState() are asynchronous in javascript. Say, if you have the following code:
console.log(a);
networkRequest().then(result => console.log(result)); // networkRequest() is a promise
console.log(b);
The a and b will get printed first followed by the result of the network request.
Similarly, this.setState() is also asynchronous so, if you want to execute something after this.setState() is completed, you need to do it as:
this.setState({data: rankrequests.data}, () => {
// Your code that needs to run after changing state
})
React Re-renders every time this.setState() gets executed, hence you are getting your component updated before the whole promise gets resolved. This problem can be solved by making your componentDidMount() as async function and using await to resolve the promise:
async componentDidMount() {
let rankrequests;
try {
rankrequests = await this.makeRankRequestCall() // result contains your data
} catch(error) {
console.error(error);
}
this.setState({ data: rankrequests.data, loading: false }, () => {
// anything you need to run after setting state
});
}
Hope it helps.
I too am having a hard time understanding what you are attempting to do here so I took a stab at it.
Since the this.setState() method is intended to trigger a render, I would not ever call it until you are ready to render. You seem to relying heavily on the state variable being up to date and able to be used/manipulated at will. The expected behaviour here, of a this.state. variable, is to be ready at the time of render. I think you need to use another more mutable variable that isn't tied to states and renders. When you are finished, and only then, should you be rendering.
Here is your code re-worked to show this would look:
import dummydata_rankrequests from "../dummydata/rankrequests";
class RankRequestList extends Component {
constructor(props) {
super(props);
/*
Maybe here is a good place to model incoming data the first time?
Then you can use that data format throughout and remove the heavier modelling
in the render function below
if (this.state.data && this.state.data.length > 0) {
data = this.state.data.map(rr => {
return Object.assign({}, rr);
});
}
*/
this.state = {
error: null,
loading: false,
data: (dummydata_rankrequests || []),
};
//binding to 'this' context here is unnecessary
//this.makeRankRequestCall = this.makeRankRequestCall.bind(this);
//this.renderItem = this.renderItem.bind(this);
}
componentDidMount() {
// this.setState({ data: dummydata_rankrequests.data, loading: false });
//Context of 'this' is already present in this lifecycle component
this.makeRankRequestCall(this.state.data).then(returnedData => {
//This would have no reason to be HERE before, you were not returning anything to get here
//Also,
//should try not to use double quotes "" in Javascript
//Now it doesn't matter WHEN we call the render because all functionality had been returned and waited for
this.setState({ data: returnedData, loading: false });
}).catch(error => {
console.log('_makeRankRequestCall-promisecatch', error);
this.setState({ error: RRError.getRRError(error), loading: false });
});
}
//I am unsure why you need a bigger call here because the import statement reads a JSON obj in without ASync wait time
//...but just incase you need it...
async makeRankRequestCall(currentData) {
try {
return new Promise((resolve, reject) => {
resolve(dummydata_rankrequests);
}).then(rankrequests => {
return Promise.resolve(rankrequests);
}).catch(error => {
return Promise.reject(error);
});
} catch (error) {
return Promise.reject(error);
}
}
renderItem(data) {
const height = 200;
//This is usually where you would want to use your data set
return (
<View style={[styles.item, {height: height}]} />
);
/*
//Like this
return {
<View style={[styles.item, {height: height}]}>
{ data.item.somedataTitleOrSomething }
</View>
};
*/
}
render() {
let data = [];
//This modelling of data on every render will cause a huge amount of heaviness and is not scalable
//Ideally things are already modelled here and you are just using this.state.data
if (this.state.data && this.state.data.length > 0) {
data = this.state.data.map(rr => {
return Object.assign({}, rr);
});
}
console.log('render-data', data);
return (
<View style={styles.container}>
<FlatList
data={data}
style={styles.listContainer1}
renderItem={this.renderItem.bind(this)} />
{ /* Much more appropriate place to bind 'this' context than above */ }
</View>
);
}
}
The setState is indeed asynchronous. I guess makeRankRequestCall should be like this:
async makeRankRequestCall() {
console.log('call makeRankRequestCall');
try {
const rankrequests = await new Promise((resolve, reject) => {
resolve(dummydata_rankrequests);
});
console.log('START makeRankRequestCall-rankrequests', rankrequests);
this.setState({ data: rankrequests.data, loading: false });
console.log('END _makeRankRequestCall-rankrequests');
} catch(error) {
console.log('_makeRankRequestCall-catch', error);
this.setState({ error: RRError.getRRError(error), loading: false });
}
}
Secondly, promise catching an error of renderItem is perfectly fine. In JavaScript, any catch block will catch any error that is being thrown anywhere in the code. According to specs:
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
So in order to fix it, if you expect renderItem to fail, you could do the following:
renderItem(data) {
const height = 200;
let item = 'some_default_item';
try {
// Force a Unknown named module error here
item = styles.item
} catch(err) {
console.log(err);
}
return (
<View style={[item, {height: height}]}>
</View>
);
}

React Native - Device back button handling

I want to check if there are more than one screens are on stack when device back button is hit. If yes, I want to show previous screen and if no, I want to exit app.
I have checked number of examples but those use BackAndroid and Navigator. But both of them are deprecated. BackHandler is replacement for BackAndroid. And I can show previous screen by using props.navigation.goBack(null).
But I am unable to find code for finding screen count in stack. I don't want to use deprecated Navigator!
This example will show you back navigation which is expected generally in most of the flows. You will have to add following code to every screen depending on expected behavior. There are 2 cases:
1. If there are more than 1 screen on stack, device back button will show previous screen.
2. If there is only 1 screen on stack, device back button will exit app.
Case 1: Show previous screen
import { BackHandler } from 'react-native';
constructor(props) {
super(props)
this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
}
componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
}
handleBackButtonClick() {
this.props.navigation.goBack(null);
return true;
}
Important: Don't forget to bind method in constructor and to remove listener in componentWillUnmount.
Case 2: Exit App
In this case, no need to handle anything on that screen where you want to exit app.
Important: This should be only screen on stack.
In functional component:
import { BackHandler } from "react-native";
function handleBackButtonClick() {
navigation.goBack();
return true;
}
useEffect(() => {
BackHandler.addEventListener("hardwareBackPress", handleBackButtonClick);
return () => {
BackHandler.removeEventListener("hardwareBackPress", handleBackButtonClick);
};
}, []);
import { BackHandler } from 'react-native';
constructor() {
super();
this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
}
componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
}
handleBackButtonClick() {
//this.props.navigation.goBack(null);
BackHandler.exitApp();
return true;
}
handleBackButtonClick() {
return true; // when back button don't need to go back
}
In Functional Component
import { BackHandler } from 'react-native';
function handleBackButtonClick() {
navigation.goBack();
return true;
}
useEffect(() => {
BackHandler.addEventListener('hardwareBackPress', handleBackButtonClick);
return () => {
BackHandler.removeEventListener('hardwareBackPress', handleBackButtonClick);
};
}, []);
In a case where there are more than one screens stacked in the stack, the default back button behavior in react-native is to navigate back to the previous screen in the stack. Handling the device back button press when having only one screen to exit the app requires a custom setting. Yet this can be achieved without having to add back handling code to each and every screen by modifying the getStateForAction method of the particular StackNavigator's router.
Suppose you have the following StackNavigator used in the application
const ScreenStack = StackNavigator(
{
'Screen1': {
screen: Screen1
},
'Screen2': {
screen: Screen2
},
},
{
initialRouteName: 'Screen1'
}
);
The getStateForAction method of the stack navigator's router can be modified as follows to achieve the expected back behavior.
const defaultStackGetStateForAction =
ScreenStack.router.getStateForAction;
ScreenStack.router.getStateForAction = (action, state) => {
if(state.index === 0 && action.type === NavigationActions.BACK){
BackHandler.exitApp();
return null;
}
return defaultStackGetStateForAction(action, state);
};
the state.index becomes 0 only when there is one screen in the stack.
Here is how I implemented successfully using certain condition:
componentWillMount() {
BackHandler.addEventListener(
'hardwareBackPress',
this.handleBackButtonClick,
);
}
componentWillUnmount() {
BackHandler.removeEventListener(
'hardwareBackPress',
this.handleBackButtonClick,
);
}
handleBackButtonClick = () => {
//some condition
if (this.state.isSearchBarActive) {
this.setState({
isSearchBarActive: false,
});
this.props.navigation.goBack(null);
return true;
}
return false;
};
React Native Hooks has a nice useBackHandler hook which simplifies the process of setting up event listeners for Android back button.
import { useBackHandler } from '#react-native-community/hooks'
useBackHandler(() => {
if (shouldBeHandledHere) {
// handle it
return true
}
// let the default thing happen
return false
})
try this
react navigation
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
}
handleBackButton = () => {
const pushAction = StackActions.push({
routeName: 'DefaultSelections',
});
this.props.navigation.dispatch(pushAction);
}
current screen is "DefaultSelections" , on back button press, would be shifted on to the same and hence back button disabled work around, as disabling back button by
return true
for backButton ( as suggested by the official docs ) disables back button on all screens ; not wanted
an utility function could be very helpful:
backPressHandler.js
import React from 'react';
import {BackHandler} from 'react-native';
const onBackPress = (callback) => {
BackHandler.addEventListener('hardwareBackPress', callback);
return () => {
BackHandler.removeEventListener('hardwareBackPress', callback);
};
};
export {onBackPress};
now in my screen:
myScreen.js
import {onBackPress} from '../utils/backPressHandler';
function handleBackPress() {
navigation.goBack();
return true;
}
useEffect(() => {
onBackPress(handleBackPress);
}, []);
I am on v0.46.0 of react-native and had the same issue. I tracked the issue down to this file in the react-native code base
https://github.com/facebook/react-native/blob/master/Libraries/Utilities/BackHandler.android.js#L25
When running with the chrome debugger turned off the line
var subscriptions = Array.from(_backPressSubscriptions.values()).reverse()
always returns an empty array for subscriptions which in turn causes the invokeDefault variable to stay true and the .exitApp() function to be called.
After more investigation, I think the issue was discovered and discussed in the following PR #15182.
Even after copy/pasting the PR change in an older version of RN it did not work most likely caused by the issue described in the PR.
After some very slight modifications I got it working by changing to
RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function() {
var invokeDefault = true;
var subscriptions = []
_backPressSubscriptions.forEach(sub => subscriptions.push(sub))
for (var i = 0; i < subscriptions.reverse().length; ++i) {
if (subscriptions[i]()) {
invokeDefault = false;
break;
}
}
if (invokeDefault) {
BackHandler.exitApp();
}
});
Simply using a .forEach which was the original implementation on the PR before the amended Array.from syntax works throughout.
So you could fork react-native and use a modified version, submit a PR though I imagine that will take a little while to be approved and merged upstream, or you can do something similar to what I did which was to override the RCTDeviceEventEmitter.addListener(...) for the hardwareBackPress event.
// other imports
import { BackHandler, DeviceEventEmitter } from 'react-native'
class MyApp extends Component {
constructor(props) {
super(props)
this.backPressSubscriptions = new Set()
}
componentDidMount = () => {
DeviceEventEmitter.removeAllListeners('hardwareBackPress')
DeviceEventEmitter.addListener('hardwareBackPress', () => {
let invokeDefault = true
const subscriptions = []
this.backPressSubscriptions.forEach(sub => subscriptions.push(sub))
for (let i = 0; i < subscriptions.reverse().length; i += 1) {
if (subscriptions[i]()) {
invokeDefault = false
break
}
}
if (invokeDefault) {
BackHandler.exitApp()
}
})
this.backPressSubscriptions.add(this.handleHardwareBack)
}
componentWillUnmount = () => {
DeviceEventEmitter.removeAllListeners('hardwareBackPress')
this.backPressSubscriptions.clear()
}
handleHardwareBack = () => { /* do your thing */ }
render() { return <YourApp /> }
}
constructor(props){
super(props)
this.onBackPress = this.onBackPress.bind(this);
}
componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', this.onBackPress);
}
componentWillUnmount(){
BackHandler.removeEventListener('hardwareBackPress', this.onBackPress);
}
onBackPress(){
const {dispatch, nav} = this.props;
if (nav.index < 0) {
return false;
}
dispatch(NavigationActions.back());
return true;
}
render(){
const {dispatch, nav} = this.props;
return(
<DrawerRouter
navigation= {
addNavigationHelpers({
dispatch,
state: nav,
addListener,
})
}
/>
);
}
If you use react-navigation, the other answers did not work for me but this did:
const handleGoBack = useCallback(() => {
// custom logic here
return true; // Returning true from onBackPress denotes that we have handled the event
}, [navigation]);
useFocusEffect(
React.useCallback(() => {
BackHandler.addEventListener('hardwareBackPress', handleGoBack);
return () =>
BackHandler.removeEventListener('hardwareBackPress', handleGoBack);
}, [handleGoBack]),
Here is the link to the documentation
useFocusEffect(
React.useCallback(() => {
const onBackPress = () => {
navigation.navigate('Journal');
return true;
};
BackHandler.addEventListener('hardwareBackPress', onBackPress);
return () => {
BackHandler.removeEventListener('hardwareBackPress', onBackPress);
};
}, []),
);
`
import { useFocusEffect} from '#react-navigation/native';
export default function App(props: any) {
function handleBackButton() {
navigation.goBack();
return true;
}
useFocusEffect(
React.useCallback(() => {
BackHandler.addEventListener("hardwareBackPress", handleBackButton);
return () => {
console.log("I am removed from stack")
BackHandler.removeEventListener("hardwareBackPress", handleBackButton);
};
}, [])
);
}
I used flux for navigation.
const RouterComp = () => {
let backLoginScene=false;
return (
<Router
backAndroidHandler={() => {
const back_button_prohibited = ['login','userInfo','dashboard'];
if (back_button_prohibited.includes(Actions.currentScene) ) {
if (backLoginScene == false) {
ToastAndroid.show("Click back again to exit.", ToastAndroid.SHORT);
backLoginScene = !backLoginScene;
setTimeout(() => {
backLoginScene = false;
}, 2000);
return true;
} else {
backLoginScene = false;
BackHandler.exitApp();
}
return false;
}}}>
<Scene key='root' hideNavBar>
<Scene key='guest' hideNavBar >
<Scene key='login' component={Login} ></Scene>
<Scene key='userInfo' component={UserInfo}></Scene>
</Scene>
<Scene key='user' hideNavBar>
<Scene key='dashboard' component={Dashboard} title='Dashboard' initial />
<Scene key='newAd' component={NewAd} title='New Ad' />
</Scene>
</Scene>
</Router>
)
}
export default RouterComp;