Doubt Basic variables Javascript

Asked

Viewed 52 times

0

Good afternoon!

I have a beginner’s question and unfortunately I am not able to find a language tutorial (who has a link please put in the answers), I just want to show the contents of variables 'ping' and 'connectado' however I am not able to do this.

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Button} from 'react-native';

import NetInfo from '@react-native-community/netinfo';
import Ping from 'react-native-ping';

var ping, connectado;

export default class App extends Component {

  render() {
    NetInfo.isConnected.fetch().then(isConnected => {
      console.log("Is connected", isConnected);
      connectado = isConnected;
    });

    (async () => {
      try {
        ms = await Ping.start('www.google.com',{ timeout: 1000 });
        console.log(ms);
        ping = ms;
      } catch (error) {
        console.log('special code',error.code, error.message);
      }
    })();

    return (
        <View style={styles.container}>
          <Text style={styles.welcome}>MS: {ping}</Text>
          <Text style={styles.welcome}>Connectado: {connectado}</Text>
        </View>    
    );
  }
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

2 answers

1


Says Gustavo. You need to put this inside the state. React is reactive, so by changing the state it "reacts" and renders the components again.

export default class App extends Component {
state = {
  ping: "",
  connectado: "",
};
  render() {
    NetInfo.isConnected.fetch().then(isConnected => {
      console.log("Is connected", isConnected);
      this.setState({ conectado: isConnected });
    });

    (async () => {
      try {
        ms = await Ping.start('www.google.com',{ timeout: 1000 });
        console.log(ms);
        this.setState({ ping: ms });
      } catch (error) {
        console.log('special code',error.code, error.message);
      }
    })();

    return (
        <View style={styles.container}>
          <Text style={styles.welcome}>MS: {this.state.ping}</Text>
          <Text style={styles.welcome}>Connectado: {this.state.connectado}</Text>
        </View>    
    );
  }
}
...

Maybe I would just put the functions into the IdMount component

0

Gustavo, it is necessary to create a state (State) in React-Native. It also has React Hooks, which allows us to work with component states in the function format.

state = {
  ping: "",
  connectado: "",
};

To change the State use the setState

Browser other questions tagged

You are not signed in. Login or sign up in order to post.