Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

278
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda