Skip to content
Advertisement

Why does my app connect to my TCP server multiple times in my react native app?

When I run the code, it connects to my TCP server multiple times even though I am expecting it to connect only once

import React, { useEffect, useState, Component }  from 'react';
import { Text, View, StyleSheet, Image, Button } from 'react-native';
import { Touchable, TouchableOpacity } from 'react-native-web';
var net = require('react-native-tcp-socket');
var cert= require('./certificate.pem');


export default function AssetExample() {;
    const [out, outfunc] = useState('Connecting...');
    const [count, countfunc] = useState(0);
        const client = net.createConnection(
        { port: 4242, host: '192.168.1.108', tls: true, tlsCheckValidity: false, tlsCert: cert  },
        () => {
        console.log("Connected");
        client.write("1");
        client.write("2");
        client.write("3");
        client.write("4");
        })
        client.on("data", function (data) {
            console.log(data);
            var dat = data.toString();
            countfunc(count + 1);
            outfunc(out + "n" + dat);
            if (data == "") {
              console.log("discon");
            }
            if (dat == "ACCGNT") {
              console.log("GRANTED");
            if (dat == "ALRCON"){
                client.destroy();
            }
              
            }}); 
//            client.destroy();
        
    return (
        <View>
            <Text>{count}</Text>
          <Text>
            {out}
          </Text>
        </View>
      );

}

The output is also changing a lot and it does not seem to follow how I programmed it to look. The output seems to be flicking from many other outputs.

Advertisement

Answer

React triggers your function multiple times during rendering. But doesn’t rerender the UI. so whatever js code inside the function will be executed every time. SO to avoid you need to move the connection logic to useEffect hook

useEffect(()=>{
// establish connection 
return ()=>{ 
// destroy connection
} 
},[])

Now the connection will happen only once. if you to reconnect based on some state. add that state in dependency array.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement