Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
'result' stays null even when I put in the correct number

I don't get any errors but when I run the React Native app result will stay false. When I click on Generate Number - undefined will print to the console, but a random number will appear under the TextInput and when I click again, a new number will appear but the old number will be printed to the console. This is my code:

import React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet } from 'react-native';

const App = () => {
  const [number, setNumber] = useState();
  const [result, setResult] = useState(false);

  const styles = StyleSheet.create({
    ...
  });

  const guess = (num) => {
    if (num === number) {
      setResult(true);
    } else {
      setResult(false);
    }
    console.log(result);
  };

  const genNumber = () => {
    setNumber(Math.floor(Math.random() * (100 - 1) + 1));
    console.log(number);
  };

  return (
    <View style={styles.view}>
      <Button onPress={() => genNumber()} title="Generate Number" />
      <TextInput
        style={styles.text}
        onChangeText={(text) => guess(text)}
        placeholder="Enter your guess"
      />
      <Text style={styles.text}>{number}</Text>
    </View>
  );
};

export default App;

Its probably a scope error but im not sure.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

useState is asynchronous, as mentioned in the comment, so you either can subscribe to a state changes with useEffect or you can do this:

const genNumber = async () => {
  await setNumber(Math.floor(Math.random() * (100 - 1) + 1));
  console.log(number);
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda