Ulysses
Ulysses

Reputation: 27

React native doesn't update state after autocomplete in textinput

I'm working on a messaging app with the following code:

const MessageCentral = () => {
  const [inputText, onChangeText] = useState('');
  const [bodyText, updateText] = useState("");

  const addMessage = () => {
    updateText(bodyText +  inputText + "\n" );
  }

  const pressSend = () => {
    addMessage();
  }
  return (
    <SafeAreaView style= {StyleSheet.safeContainer}>
      <View style={styles.container}>
        <ScrollView 
        ref={scrollView =>this.scrollView = scrollView}
        onContentSizeChange={scrollView.scrollToEnd({animated: true})}
        style={styles.messageContainer}>
            <Text>
              {bodyText.toString()}
            </Text>
        </ScrollView>
   
        <View style={styles.inputContainer}>

          <TextInput 
            style={styles.messageInput}
            onChangeText={text => onChangeText(text)}
            value={inputText}
          />
          <Button 
          style={styles.sendButton}
            icon = { <Icon
              name= "activity"
              size={25}  
              color="blue"  
              />           
            }
            onPress={() => {
              pressSend();
        
            }}
          />
    
        </View>
      </View>
    </SafeAreaView>
  )
}

On the iOS emulator, when I enter some text without autocomplete and press the send button, the bodyText updates as it is supposed to. If I use autocomplete for the last word and press enter, bodyText is updated with the inputText before the autocomplete. How can I fix this?

Upvotes: 3

Views: 366

Answers (0)

Related Questions