I encountered an issue with TextInput, which gets input from user, and a button which send the message in TextInput and clear the input. So overall flow would be:
- User type into TextInput
- At some point, user presses Button(aka. TouchableOpacity)
- Store the text from the TextInput to temporary buffer then clear the TextInput.
- Send the text via api.
Code looks like:
{/* Message Input */}
<TextInput
style={styles.messageInput}
multiline
onChangeText={text => {
setMessage(text);
}}
value={message}
/>
{/* Send Button */}
<Button
title={"Send"}
onPress={() => {
const msg = message
onSendMessage(msg);
setMessage("");
}}
disabled={false}
style={styles.sendButton}
/>
And my problem occurs when user type too soon after tapping the send button. If user decides to type too soon, then TextInput does not get cleared. I think this is because:
- User tap send => enqueues render because message state change by setMessage("") in Button's onPress
- User type too soon => enqueues render because message change by onChangeText handler in TextInput. The problem is setMessage from previous state hasn't been really handled yet. Therefore, this render is enqueued with message's previous value (aka. value before message was set to "" ).
I tried Promise, useEffect, and useRef, but nothing really solved this issue. If anyone knows how to overcome with this issue, please let me know. Thank you in advance.