0
votes

attempting to programmatically disconnect from a socket.io connection once the nav-bar back button is pressed.

I've tried handling button presses according to Wix GitHub documentation here: https://wix.github.io/react-native-navigation/#/docs/topBar-buttons?id=handling-button-press-events

export default class Lobby extends React.Component {
  static options(passProps) {
    return {
      topBar: {
        leftButtons: {
          id: "backButton"
        }
      }
    };
  }

  constructor(props) {
    super(props);
    this.state = {
      username: "",
      queue: []
  };
    Navigation.events().bindComponent(this);
  }
// for the parameter I've tried: `{buttonId}`, `{backButton}`,`"backButton"`, `backButton`
      navigationButtonPressed(backButton) {
        const socket = io("http://172.31.99.250:3000");
         socket.emit("leaveLobby", this.state.username);
      }

Nothing from the handler function happens. the Apps just goes back to the previous page without sending the socket.io event

2

2 Answers

0
votes

just use like this in

react-native-navigation v2

   import {BackHandler} from 'react-native'

   ...


    constructor(props){
        super(props)
        Navigation.events().bindComponent(this)
    }

    componentDidDisappear() {
        BackHandler.removeEventListener('hardwareBackPress',this.handleBackPress);
    }

    componentDidAppear() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
    }

    handleBackPress = () => {
        this.moveToHome()
        return true
    }

    moveToHome = () => {
        Navigation.mergeOptions("maintabs", {
            bottomTabs: {
                  currentTabIndex: 0,
            }
      })
    }
...
0
votes

you have to use this methode as follow to run your function

navigationButtonPressed({ buttonId }) {

let isRTL = this.checklanguage();

switch (buttonId) {
  case 'menuBtn':     // id of your navigation item
    this.toggleSideMenu(isRTL);    // func to run  
    break;
  case 'logoutBtn':
    this.logoutHandler();
    break;

  default:
    break;
}

}

your code has bug as it work on Object an you didn't provide it on in your code

// for the parameter I've tried: `{buttonId}`, `{backButton}`,`"backButton"`, `backButton`
  navigationButtonPressed(backButton) {
    const socket = io("http://172.31.99.250:3000");
     socket.emit("leaveLobby", this.state.username);
  }

try mine one