Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
'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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!