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.
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);
};