Why is socket.on() from a previous screen component executed? - javascript

I have two react components. the first Lobby uses react-native-navigation to push Gameroom to the stack. It passes props such as the socket object and other data to the Gameroom component
when the back button of the navigation bar is pressed inside Gameroom, a socket.io leave event is emitted, and I have verified it is heard by the server, so the socket passed through props works. the server then emits an event left back to the socket.io room (Gameroom component).
the left event listener, if placed inside Gameroom's componentDidMount() does not execute. However, if the same socket.io event listener is placed in Lobby component (previous screen) componentDidMount() the event is heard
I've tried adding the event listener to multiple componentDidMount functions, I also thought about using the Context API, but I'm not working with nested components. I'm passing the socket object in react-native-navigation's {passProps} from screen to screen
Lobby:
imports ...
const socket = io("http://192.xxx.xxx.xx:3000");
export default class Lobby extends React.Component {
static options(passProps) {
return {
topBar: {
background: {
color: "transparent"
},
drawBehind: true,
visible: true,
animate: true,
leftButtons: [
{
id: "leave",
icon: require("../assets/img/Chevron.png")
}
]
}
};
}
constructor(props) {
super(props);
this.state = {
username: "Initializing...",
queue: []
};
}
componentDidMount() {
Navigation.events().bindComponent(this);
socket.emit("lobbyEntry");
socket.on("lobbyEntry", entry => {
this.setState({ queue: entry.lobby, username: socket.id });
});
socket.on("userJoined", lobby => {
this.setState({ queue: lobby });
});
// socket.on("left", () => {
// alert("Opponent Left...Oh well");
// Navigation.pop(this.props.componentId);
// });
}
navigationButtonPressed({ buttonId }) {
switch (buttonId) {
case "leave":
socket.emit("leave");
Navigation.popToRoot(this.props.componentId);
break;
}
}
createMatch = () => {
if (this.state.username != "Initializing...") {
socket.emit("findMatch");
socket.on("alreadyCreated", () => {
alert("You already created a match!");
});
socket.on("listUsers", lobby => {
this.setState({ queue: lobby });
});
socket.on("matchFound", data => {
Navigation.push(this.props.componentId, {
component: {
name: "Gameroom",
passProps: {
room: data.id,
socket: socket,
firstMove: data.firstMove,
p1: data.p1,
p2: data.p2
}
}
});
});
} else {
alert("Wait for Username to be initialized...");
}
};
render() {
const bg = getBackground();
return (
<ImageBackground source={bg} style={{ height: "100%", width: "100%" }}>
<View style={styles.title_container}>
<Text style={styles.title_sm}>Matchmaking Lobby</Text>
</View>
<View style={styles.alt_text_container}>
<Text style={styles.alt_text_md}>Username:</Text>
<Text style={styles.alt_text_md}>{this.state.username}</Text>
</View>
<View
style={{
flexDirection: "column",
justifyContent: "center",
alignItems: "center"
}}
>
<XplatformButton onPress={this.createMatch} text={"Create a Match"} />
</View>
<View style={styles.alt_text_container}>
<Text style={styles.alt_text_sm}>Players actively searching...</Text>
<FlatList
style={styles.alt_text_container}
data={this.state.queue}
renderItem={({ item, index }) => (
<Text style={styles.alt_text_md} key={index}>
{item}
</Text>
)}
/>
</View>
</ImageBackground>
);
}
}
Gameroom:
import ...
export default class Gameroom extends React.Component {
static options(passProps) {
return {
topBar: {
title: {
fontFamily: "BungeeInline-Regular",
fontSize: styles.$navbarFont,
text: "Gameroom - " + passProps.room,
color: "#333"
},
background: {
color: "transparent"
},
drawBehind: true,
visible: true,
animate: true,
leftButtons: [
{
id: "leave",
icon: require("../assets/img/Chevron.png")
}
]
}
};
}
constructor(props) {
super(props);
Navigation.events().bindComponent(this);
}
navigationButtonPressed({ buttonId }) {
switch (buttonId) {
case "leave":
this.props.socket.emit("leave");
Navigation.pop(this.props.componentId);
break;
}
}
componentDidMount() {
// socket.on("left", () => {
// alert("Opponent Left...Oh well");
// Navigation.pop(this.props.componentId);
// });
}
render() {
const bg = getBackground();
return this.props.p2 != null ? (
<Gameboard
room={this.props.room}
you={
this.props.socket.id == this.props.p1.username
? this.props.p1.marker
: this.props.p2.marker
}
opponent={
this.props.socket.id != this.props.p1.username
? this.props.p2.marker
: this.props.p1.marker
}
move={this.props.firstMove}
socket={this.props.socket}
/>
) : (
<ImageBackground style={styles.container} source={bg}>
<View style={{ marginTop: 75 }}>
<Text style={styles.alt_text_md}>
Waiting for Opponent to Join...
</Text>
</View>
</ImageBackground>
);
}
}
I expect the event listener to execute from the current screen's componentDidMount() function, but it only executes if it's inside the previous screen's componentDidMount()

When you create a component,
the constructor -> componentWillMount -> render -> componentDidMount is
followed.
In your Lobby class, the event listener is run because it is in ComponentDidmont.
However, the event listener of the Gameroom class is inside the constructor. If executed within the constructor, the event cannot be heard because it is not yet rendered.
Event listeners are called when they appear on the screen
Usage
componentDidMount() {
this.navigationEventListener = Navigation.events().bindComponent(this);
}
componentWillUnmount() {
// Not mandatory
if (this.navigationEventListener) {
this.navigationEventListener.remove();
}
}

Related

How to handle volumes of multiple track in react-native sound, i want to play 2 sound together and if i want to decrease sound of one

Here is my code screen code
import React, {Component} from 'react';
import {StyleSheet, Text, TouchableOpacity, View, ScrollView, Alert} from 'react-native';
import Sound from 'react-native-sound';
import BgSoundPlayer from '../../../../Components/BgSoundPlayer/BgSoundPlayer';
const audioTests = [
{
title: 'mp3 remote download',
url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3',
},
{
title: "mp3 remote - file doesn't exist",
url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-9.mp3',
},
];
const Button = ({title, onPress}) => (
<TouchableOpacity onPress={onPress}>
<Text style={styles.button}>{title}</Text>
</TouchableOpacity>
);
const Header = ({children, style}) => <Text style={[styles.header, style]}>{children}</Text>;
const Feature = ({
title,
onPress,
buttonLabel = 'PLAY',
status,
volumeIncrease,
volumeDecrease,
}) => (
<View style={styles.feature}>
<Header style={{flex: 1}}>{title}</Header>
{status ? <Text style={{padding: 5}}>{resultIcons[status] || ''}</Text> : null}
<Button title={buttonLabel} onPress={onPress} />
<Button title="Volume Increase" onPress={volumeIncrease} />
<Button title="volume Decrease" onPress={volumeDecrease} />
</View>
);
const resultIcons = {
'': '',
pending: '?',
playing: '\u25B6',
win: '\u2713',
fail: '\u274C',
};
function setTestState(testInfo, component, status) {
component.setState({tests: {...component.state.tests, [testInfo.title]: status}});
}
/**
* Generic play function for majority of tests
*/
function playSound(testInfo, component) {
setTestState(testInfo, component, 'pending');
BgSoundPlayer.setSound(testInfo);
}
class MainView extends Component {
constructor(props) {
super(props);
Sound.setCategory('Playback', true); // true = mixWithOthers
// Special case for stopping
this.stopSoundLooped = () => {
if (!this.state.loopingSound) {
return;
}
this.state.loopingSound.stop().release();
this.setState({
loopingSound: null,
tests: {...this.state.tests, ['mp3 in bundle (looped)']: 'win'},
});
};
this.state = {
loopingSound: undefined,
tests: {},
};
}
render() {
return (
<View style={styles.container}>
<ScrollView style={styles.container} contentContainerStyle={styles.scrollContainer}>
{audioTests.map(testInfo => {
return (
<Feature
status={this.state.tests[testInfo.title]}
key={testInfo.title}
title={testInfo.title}
onPress={() => {
playSound(testInfo, this);
}}
volumeIncrease={() => {
BgSoundPlayer.increaseVolume();
}}
volumeDecrease={() => {
BgSoundPlayer.decreaseVolume();
}}
/>
);
})}
<Feature
title="mp3 in bundle (looped)"
buttonLabel={'STOP'}
onPress={() => {
BgSoundPlayer.pouse();
}}
/>
</ScrollView>
</View>
);
}
}
export default MainView;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'gray',
},
scrollContainer: {},
title: {
fontSize: 20,
fontWeight: 'bold',
paddingTop: 30,
padding: 20,
textAlign: 'center',
backgroundColor: 'rgba(240,240,240,1)',
},
button: {
fontSize: 20,
backgroundColor: 'rgba(220,220,220,1)',
borderRadius: 4,
borderWidth: 1,
borderColor: 'rgba(80,80,80,0.5)',
overflow: 'hidden',
padding: 7,
},
header: {
textAlign: 'left',
},
feature: {
padding: 10,
borderTopWidth: 1,
borderBottomWidth: 1,
},
});
And my BgSoundPlayer file
import {Alert} from 'react-native';
import Sound from 'react-native-sound';
Sound.setCategory('Playback', true);
class BgSoundPlayer1 {
setSound(soundURL) {
try {
this.soundURL = soundURL;
if (soundURL.isRequire) {
this.soundRef = new Sound(soundURL.url, error =>
this.callback(error, this.soundRef),
);
} else {
this.soundRef = new Sound(soundURL.url, Sound.MAIN_BUNDLE, error =>
this.callback(error, this.soundRef),
);
}
} catch (error) {
console.log('SOUNDREFERROR::', error);
}
}
callback(error, sound) {
try {
if (error) {
Alert.alert('error', error.message);
return;
}
//this.soundURL.onPrepared && this.soundURL.onPrepared(sound);
sound.play(() => {
sound.release();
});
} catch (error) {
console.log('CALL_BACKERROR::', error);
}
}
getVolume() {
return this.soundRef?.getVolume();
}
increaseVolume(soundURL) {
console.log('CHECKREF', this.soundRef);
let sound = this.soundRef?.getVolume();
if (sound < 1 || sound == 1) {
this.soundRef?.setVolume(sound + 0.1);
}
}
decreaseVolume(soundURL) {
console.log('CHECKREF', this.soundRef);
let sound = this.soundRef?.getVolume();
if (sound > 0 || sound == 0) {
this.soundRef?.setVolume(sound - 0.1);
}
}
pouse() {
this.soundRef?.pause();
}
}
const BgSoundPlayer = new BgSoundPlayer1();
export default BgSoundPlayer;
So what is happening right now if, when I am playing one audio track and increasing decreasing volume of track its working fine
but problem occurre's when I play second track and decrease sound of first one, it dosent works it decrease volume of second track
but when I tried to debug problem, I got to know that my this.soundRef variable is taking the refrance of latest one sound, so how can solve this

Add WebView via onClick in Expo React-Native

I need a function that creates new screens with a webview in it.
The main screen of my expo app contains a button "add new Page" which links to a page with a form to add domain, Username, Password.
if this is done, I want a list of pages in my main screen with all pages. for example if I click on "myWebsite1" with the generated link http://user:password#myWebsite1.com this page should be shown in a webview. same for website2, 3 and so on.
Anyone an idea how to do this?
EDIT: I add some code I have right now. For each Task I create, the Domain, User and Password for the webview file should change and be saved at this specific task. (and also open onclick). I turn in a circle
this is my app.js which expo opens first, it contains a Flatlist:
import React, { Component } from "react";
import { AppRegistry, StyleSheet, Text, View, FlatList, AsyncStorage, Button, TextInput, Keyboard, Platform, TouchableWithoutFeedback } from "react-native";
const isAndroid = Platform.OS == "android";
const viewPadding = 10;
const things = {things}
export default class NodeList extends Component {
state = {
tasks: [ ],
text: ""
};
changeTextHandler = text => {
this.setState({ text: text });
};
addTask = () => {
let notEmpty = this.state.text.trim().length > 0;
if (notEmpty) {
this.setState(
prevState => {
let { tasks, text } = prevState;
return {
tasks: tasks.concat({ key: tasks.length, text: text }),
text: ""
};
},
() => Tasks.save(this.state.tasks)
);
}
};
deleteTask = i => {
this.setState(
prevState => {
let tasks = prevState.tasks.slice();
tasks.splice(i, 1);
return { tasks: tasks };
},
() => Tasks.save(this.state.tasks)
);
};
componentDidMount() {
Keyboard.addListener(
isAndroid ? "keyboardDidShow" : "keyboardWillShow",
e => this.setState({ viewMargin: e.endCoordinates.height + viewPadding })
);
Keyboard.addListener(
isAndroid ? "keyboardDidHide" : "keyboardWillHide",
() => this.setState({ viewMargin: viewPadding })
);
Tasks.all(tasks => this.setState({ tasks: tasks || [] }));
}
render() {
return (
<View
style={[styles.container, { paddingBottom: this.state.viewMargin }]}
>
<Text style={styles.appTitle}>Nodes</Text>
<FlatList
style={styles.list}
data={this.state.tasks}
renderItem={({ item, index }) =>
<View>
<View style={styles.listItemCont}>
<TouchableWithoutFeedback onPress={() => Linking.openURL('')}>
<Text style={styles.listItem}>
{item.text}
</Text>
</TouchableWithoutFeedback>
<Button color= "#00BC8C" title="✖" onPress={() => this.deleteTask(index)} />
</View>
<View style={styles.hr} />
</View>}
/>
<TextInput
style={styles.textInput}
onChangeText={this.changeTextHandler}
onSubmitEditing={this.addTask}
value={this.state.text}
placeholder="+ add Node"
returnKeyType="done"
returnKeyLabel="done"
/>
</View>
);
}
}
let Tasks = {
convertToArrayOfObject(tasks, callback) {
return callback(
tasks ? tasks.split("||").map((task, i) => ({ key: i, text: task })) : []
);
},
convertToStringWithSeparators(tasks) {
return tasks.map(task => task.text).join("||");
},
all(callback) {
return AsyncStorage.getItem("TASKS", (err, tasks) =>
this.convertToArrayOfObject(tasks, callback)
);
},
save(tasks) {
AsyncStorage.setItem("TASKS", this.convertToStringWithSeparators(tasks));
}
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#252525",
padding: viewPadding,
paddingTop: 24
},
list: {
width: "100%"
},
listItem: {
paddingTop: 4,
paddingBottom: 2,
fontSize: 18,
color:"#ffff"
},
hr: {
height: 1,
backgroundColor: "gray"
},
listItemCont: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingTop: 10,
},
textInput: {
height: 40,
paddingRight: 10,
paddingLeft: 10,
borderColor: "gray",
borderWidth: isAndroid ? 0 : 1,
width: "100%",
color:"#ffff"
},
appTitle: {
alignItems:"center",
justifyContent: "center",
paddingBottom: 45,
marginTop: 50,
fontSize: 25,
color:"#ffff"
}
});
AppRegistry.registerComponent("NodeList", () => NOdeList);
and here is my second screen, which contains the component for the WebView:
import React, { Component, useState } from "react";
import { BackHandler } from 'react-native';
import { WebView } from 'react-native-webview';
var $ = require( "jquery" );
export default class nodeView extends Component {
constructor(props) {
super(props);
this.WEBVIEW_REF = React.createRef();
}
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
}
handleBackButton = ()=>{
this.WEBVIEW_REF.current.goBack();
return true;
}
onNavigationStateChange(navState) {
this.setState({
canGoBack: navState.canGoBack
});
}
render(){
return (
<WebView
source={{ uri: `https://${user}:${password}#${domain}` }}
ref={this.WEBVIEW_REF}
style={{ marginTop: 20 }}
onNavigationStateChange={this.onNavigationStateChange.bind(this)}
/>
)
}
}
Create WebView. Create State Which Controls WebView. Add Listener To Button

React Native elements not rendering as expected

I am just getting started with React Native. I have created a new App using expo.io and am currently testing the components provided by https://react-native-elements.github.io
I am trying out input forms and buttons my code currently looks like this:
class EnterNewPasswordComp extends React.Component {
constructor(props) {
super(props);
this.state = {
pass : ''
}
}
render() {
return <View style={styles.container}>
<Text style={styles.label}>{pass_label}</Text>
<Input placeholder='Password' />
<Text style={styles.note}>{pass_desc}</Text>
<Button title="Submit" type="outline" />
</View>;
}
}
const styles = {
container : {
flex : 1,
justifyContent: 'center',
alignItems: 'center',
},
label : {
fontSize: 20,
},
note : {
fontSize: 12,
marginBottom: 20
},
input : {
color : style.txtcolor
},
btn : {
width : '50%'
}
};
the component (currently) only returning the EnterNewPasswordComp
class IndexComponent extends React.Component {
constructor(props) {
super(props);
this.passDao = Factory.getPasswordDao();
this.state = {
status: 'initializing'
}
}
async componentDidMount() {
try {
const pass = await this.passDao.getPassword();
logger.info(pass);
const setupNeeded = pass === null;
if( setupNeeded ) {
this.setState({
status : 'setup'
});
}
else {
this.setState({
status : 'ready'
})
}
} catch (e) {
logger.error("Error during db query", e);
this.setState({
status: 'corrupted'
});
}
}
render() {
let msg = "initializing";
switch (this.state.status) {
case 'initializing':
msg = 'initializing';
break;
case 'corrupted':
default:
msg = 'corrupted';
break;
case 'ready':
msg = 'ready';
break;
case 'setup':
return <EnterNewPasswordComp/>
}
return <Text>{msg}</Text>
}
}
and this component is used in my App.js like this:
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<IndexComponent/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}
});
This is how my output looks like on my Android Phone:
Note that:
The input field is not rendering at all
The button type outline is not picked up correctly
The button width is not picked up correctly
I played around with the styles, (like setting the color of the input-form, suspecting it might be the same as the background), but nothing changed at all. I am wondering if I am doing something fundamentally wrong to produce those issues.

Restart Countdown timer in react native

working on a countdown timer, I want to be able to restart the countdown onpress of the button, however, I don't think the button is functional as I get no feedback. can someone please point me in the right direction. below is a trimmed down sample code of what I am trying to achieve.
export default class Example extends Component {
constructor(props) {
super(props);
this.state = {
timer: 10,
timesup: false,
timing: true,
showWelcome: true,
};
}
componentDidMount() {
this.clockCall = setInterval(() => {
this.decrementClock();
}, 1000);
}
startTimer = () => {
this.setState({
timing: true,
timer: 30,
showWelcome: false
})
}
decrementClock = () => {
this.setState((prevstate) => ({
timer: prevstate.timer - 1
}), () => {
if (this.state.timer === 0) {
clearInterval(this.clockCall)
this.setState({
timesup: true,
timing: false,
showWelcome: false,
})
}
})
}
componentWillUnmount() {
clearInterval(this.clockCall);
}
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
{this.state.timesup && (
<Text style={{fontSize: 18, color: '#000'}}>
Time up
</Text>)}
{this.state.timing && (
<Text style={{fontSize: 18, color: '#000'}}>
{this.state.timer}
</Text>)}
{this.state.showWelcome && (
<Text style={{ fontSize: 20 }}>Welcome</Text>
)}
<Button Onpress={this.startTimer.bind(this)} title='play' />
</View>
)
}
}
I believe you're looking for onPress, not Onpress. Also, if you are using:
startTimer = () => ...
Using:
this.startTimer.bind
Has no effect, since the method is already bound to this by the arrow function. You can then simply use:
onPress={this.startTimer}

React Native Display Rendering

I updated the code to reflect Denis' solution. However, react is now no longer responding to commands sent from the node server
export default class Display extends Component {
constructor(props){
super(props);
this.state = {
ren: "",
action: "background",
media: "white",
backgroundColor: 'white',
uri: "https://www.tomswallpapers.com/pic/201503/720x1280/tomswallpapers.com-17932.jpg"
};
}
componentDidMount(){
this.startSocketIO();
}
componentWillUnmount(){
socket.off(Socket.EVENT_CONNECT);
}
startSocketIO(){
socket.on('function_received', func_var => {
let command = func_var.split(" ");
this.setState({action: command[0]});
this.setState({media: command[1]});
console.log(this.state.action);
console.log(this.state.media);
switch(this.state.action){
case 'image':
this.setState({ uri: this.state.media});
console.log(this.state.uri);
case 'background':
this.setState({ backgroundColor: this.state.media});
console.log(this.state.backgroundColor);
default:
console.log(this.state.backgroundColor);
// return (<View style={{backgroundColor: this.state.backgroundColor, flex: 1}} />);
}
});
}
render(){
return (
null
);
}
}
I'm currently working on a basic react native app that displays images received in uri format from a node server and changes the background color. Separately, both of my implementations work. (See the BackGround and ImageServer components) I'm now attempting to combine the functionality of both components into one component named display. So far my current code looks like it should work without issue however after sending a command to the device via socket.io it appears that the render doesn't go any further since my console logs stop populating after a test. I'm not sure if there is an issue with the setup of the switch statement or if I'm somehow causing a race condition. Any insight would be greatly appreciated!
import React, { Component } from 'react';
import {Image, Text, StyleSheet, Button, View, Dimensions, Vibration} from 'react-native';
const io = require('socket.io-client');
//change this to your public ip "google what is my ip address"
//This will be modified in the future to grab the ip address being used by
//the node server
let server = 'redacted';
let socket = io(server, {
transports: ['websocket']
});
export default class Display extends Component {
constructor(props){
super(props);
this.state = {
action: "background",
media: "white",
backgroundColor: 'white',
uri: "https://www.tomswallpapers.com/pic/201503/720x1280/tomswallpapers.com-17932.jpg"
};
}
render(){
socket.on('function_received', func_var => {
var command = func_var.split(" ");
this.setState({action: command[0]});
this.setState({media: command[1]});
});
console.log(this.state.action);
console.log(this.state.media);
switch(this.state.action){
case 'image':
this.setState({ uri: this.state.media});
return (
<Image
source={{uri: this.state.uri}}
style={styles.fullscreen} />
);
case 'background':
this.setState({ backgroundColor: this.state.media});
return (<View style={{backgroundColor: this.state.backgroundColor, flex: 1}} />);
default:
return (<View style={{backgroundColor: this.state.backgroundColor, flex: 1}} />);
}
}
}
export class BackGround extends Component {
constructor(props){
super(props);
this.state = {
backgroundColor: 'black'
};
}
render(){
socket.on('function_received', func_var => {
this.setState({ backgroundColor: func_var});
});
return (
<View style={{backgroundColor: this.state.backgroundColor, flex: 1}} />
);
}
}
export class ImageServer extends Component {
constructor(props){
super(props);
this.state = {
uri: "https://www.tomswallpapers.com/pic/201503/720x1280/tomswallpapers.com-17932.jpg"
};
}
render() {
socket.on('function_received', func_var => {
//Vibration.vibrate([0, 500, 200, 500,200,500,200,500,200,500,200,500,200], false);
this.setState({ uri: func_var});
});
return(
<Image
source={{uri: this.state.uri}}
style={styles.fullscreen}
/>
);
}
}
You code should like this
componentDidMount() {
this.startSocketIO();
}
startSocketIO() {
socket.on('some_method', (response) => {
this.setState({ key: response.some_value })
});
}
componentWillUnmount() {
// unsubscribe socket.io here !important
}
render() {
return (
// JSX
);
}

Categories

Resources