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

129
Visualizações
'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 Respostas
Responde à pergunta

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 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