dionidip
dionidip

Reputation: 13

react-native: back button handler

I want to detect value is changed when hardware back button pressed.

but, using BackHandler in useEffect, it is not working.

here is my code...

useEffect(() => {

  BackHandler.addEventListener("hardwareBackPress", backAction);

  return () => {
    BackHandler.removeEventListener("hardwareBackPress", backAction)
  }
},[]);

  const backAction = () => {
    BackActionAlert(
      navigation,
      addedImage.length > 0 || deletedImage.length > 0,
      'ModifyDetail'
    );
    return true;
  };
  
  const BackActionAlert = (navigation, requireBackAlert, fromWhere) => {
  if (requireBackAlert) {
    Alert.alert(
      "warning",
      alertMessage(fromWhere),
      [
        {
          text: 'NO',
          style: 'cancel',
        },
        {
          text: 'OK',
          onPress: () => navigation.goBack()
        }
      ],
      {
        cancelable: true,
      }
    );
  } else {
    navigation.goBack();
  }
};

in my code, Array addedImage and deletedImage have no element when that component mounted,

so, it return false (I guess)

How can i fix it?

Upvotes: 1

Views: 2366

Answers (1)

Kartikey
Kartikey

Reputation: 4992

Create a folder called hooks where your App.js is located

Inside hooks folder, create a file called useBackHandler.js

Inside useBackHandler.js paste this

import { useEffect } from "react";
import { BackHandler } from "react-native";

export default function useBackHandler(handler) {
  useEffect(() => {
    BackHandler.addEventListener("hardwareBackPress", handler);

    return () => BackHandler.removeEventListener("hardwareBackPress", handler);
  }, [handler]);
}

Then use it like this wherever you want to handle backpress

import useBackHandler from "path/to/hooks/and/useBackHandler.js";
// Make sure the import is correct

useBackHandler(() => {
  if (want_to_do_something) {
    // Do Something
    return true;
  }

  return false;
});

So in your case it will be used like this

useBackHandler(() => {
  if (addedImage.length > 0 || deletedImage.length > 0) {
    BackActionAlert(navigation, 'ModifyDetail');
    return true;
  }

  return false;
});

const BackActionAlert = (navigation, fromWhere) => {
  Alert.alert(
    'warning',
    alertMessage(fromWhere),
    [
      {
        text: 'NO',
        style: 'cancel',
      },
      {
        text: 'OK',
        onPress: () => navigation.goBack(),
      },
    ],
    {
      cancelable: true,
    }
  );
};

Upvotes: 2

Related Questions