The question is published on by Tutorial Guruji team.
I’m struggling to make a code that I found work.
The problem is that the functions defined inside the constructor return undefined
, so when trying to assign them when events happen, the following error appears:
Invalid type undefined for OnConnect
A mininal example is the following (full code at the end of the question)
export default class App extends Component { constructor(props) { super(props) // this is a function defined inside the constructor onConnect = () => { // some code }; // but if I try to print it, it returns undefined console.log(this.onConnect) } }
So the problem is that the definition of this functions is wrong. They use the arrow function and it looks fine to me, so I don’t know why it says it’s undefined.
Full code:
import React, { Component } from 'react'; import init from 'react_native_mqtt'; import { AsyncStorage, StyleSheet, Text, View } from 'react-native'; init({ size: 10000, storageBackend: AsyncStorage, defaultExpires: 1000 * 3600 * 24, enableCache: true, sync: {}, }); const styles = StyleSheet.create({ container: { width: '100%', height: '100%', }, }); export default class MqttLog extends Component { constructor(props) { super(props); const client = new Paho.MQTT.Client('iot.eclipse.org', 443, 'uname'); client.onConnectionLost = this.onConnectionLost; client.onMessageArrived = this.onMessageArrived; client.connect({ onSuccess: this.onConnect, useSSL: true }); this.state = { text: ['...'], client, }; } pushText = entry => { const { text } = this.state; this.setState({ text: [...text, entry] }); }; onConnect = () => { const { client } = this.state; client.subscribe('WORLD'); this.pushText('connected'); }; onConnectionLost = responseObject => { if (responseObject.errorCode !== 0) { this.pushText(`connection lost: ${responseObject.errorMessage}`); } }; onMessageArrived = message => { this.pushText(`new message: ${message.payloadString}`); }; render() { const { text } = this.state; return ( <View style={styles.container}> {text.map(entry => <Text>{entry}</Text>)} </View> ); } }
Answer
As stated in the comments: Your first example differs from the seconds as that in the first, you are creating the onConnect function within the constructor itself and in the second, it’s in a class level.
If you want it to be correct in the first, you’ll have to create it like this:
export default class App extends Component { constructor(props) { super(props) // this is a function defined inside the constructor this.onConnect = () => { // some code }; // but if I try to print it, it returns undefined console.log(this.onConnect) } }
The latter code seems correct.