Guys i’m new to React Native and also not good at JavaScript. In my app i have 2 TextInput and a Pressable button but the output is not making sense. I’ve tried to change timing of execution of some lines but result is the same.
I’m using: expo, react native 0.68.2, android api 30 (Android Studio)
output:
Android Bundling complete 32ms
First click
LOG description :
LOG identity :
Second click
LOG description :sadasdas
LOG identity :12345678910
Report.js
JavaScript
x
50
50
1
export default function Report({ route, navigation }) {
2
const [enteredText, setEnteredText] = useState("");
3
const [enteredId, setEnteredId] = useState("");
4
5
const [description, setDescription] = useState("");
6
const [identity, setIdentity] = useState("");
7
8
function descriptionInputHandler(enteredText) {
9
setEnteredText(enteredText);
10
//console.log("entered text :" + enteredText);
11
}
12
13
function identityInputHandler(enteredId) {
14
setEnteredId(enteredId);
15
//console.log("entered id :" + enteredId);
16
}
17
18
function buttonHandler() {
19
setDescription(enteredText);
20
setIdentity(enteredId);
21
setEnteredText("");
22
setEnteredId("");
23
console.log("description :" + description);
24
console.log("identity :" + identity);
25
}
26
27
return (
28
<View style={styles.container}>
29
<Text style={styles.title}>{category}</Text>
30
<View style={styles.inputContainer}>
31
<TextInput
32
style={styles.longTextInput}
33
placeholder="Describe your situation, don't worry we are here."
34
onChangeText={descriptionInputHandler}
35
value={enteredText}
36
/>
37
<TextInput
38
style={styles.textInput}
39
placeholder="What is your identity number."
40
onChangeText={identityInputHandler}
41
value={enteredId}
42
/>
43
<Pressable style={styles.button} onPress={buttonHandler}>
44
<Text style={styles.text}>Send report!</Text>
45
</Pressable>
46
</View>
47
</View>
48
);
49
}
50
Advertisement
Answer
Try something like that instead :
JavaScript
1
12
12
1
function buttonHandler() {
2
setDescription(enteredText);
3
setIdentity(enteredId);
4
}
5
6
useEffect(() => {
7
console.log("description :" + description);
8
console.log("identity :" + identity);
9
setEnteredText("");
10
setEnteredId("");
11
}, [description, identity]);
12
The useEffect should be triggered twice since both description and identity are in the dependency array but it’s a good start to manage the asynchronous behavior of useState.