Home > Blockchain >  React Native: doesn't get the latest data from an array
React Native: doesn't get the latest data from an array

Time:04-08

I have a chat app, this is just like a chatbot. So I am not using any database, all the messages are temporary. So I decided to use JavaScript arrays, whenever the user types anything in the TextInput and presses the button, it pushes that message to the array. And in another place, I am mapping everything from the array and displaying them in the screen using <Text> component. Now, the Text component isn't showing any data which is pushed to the array, it only shows the dummy messages I entered to check them. Check out the code below:

import { React, useState } from 'react';
import { Alert, ScrollView, SafeAreaView, Text, StyleSheet, TextInput, Button, TouchableHighlight, Image } from 'react-native'; 

function ChatWindow(props) {
    const [userMessage, setUserMessage] = useState("");
    const [isTextInputFocused, setFocused] = useState(false);
    const styles = StyleSheet.create({
        mainSafeAreaView: {
            flex: 1,
            backgroundColor: 'white',
        },
        bottomSafeAreaView: {
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center',
            position: 'absolute', 
            top: '93%', 
            left: '2%',
            bottom: '2%',
            marginBottom: '10%',
            flexDirection: 'row',
            justifyContent: 'space-between'
        },
        userMessageTextInput:  {
            height: 40,
            width: 300,
            borderColor: isTextInputFocused == true ? "blue" : "gray",
            alignItems: 'center', 
            borderWidth: 1,
            borderRadius: 20,
            paddingLeft: 10,
            paddingRight: 10
        },
        sendButton: { 
            marginLeft: 5,
            height: 40,
            width: 40
        },
        usersMessage: {
            backgroundColor: "#3386ff",
            borderRadius: 20,
            padding: 7,
            margin: 3,
            color: "white",
            textAlign: "center"
        },
        userMessageAreaView: {
            flexDirection: "row",
            justifyContent: "flex-end",
            marginRight: 10
        },
        botMessage: {
            backgroundColor: "#e7e0e0",
            borderRadius: 20,
            padding: 7,
            margin: 3,
            color: "black",
            textAlign: "center"
        },
        botMessageAreaView: {
            flexDirection: "row",
            justifyContent: "flex-start",
            marginLeft: 10
        },
        scrollArea: {
            marginTop: 40
        }
    }) 
    var userMessagesSent = [
        {sentBy: "user", content: "Bursa will be the capital of ottoman"},
        {sentBy: "araf", content: "Agree"}
    ];
    function sendMessage(messageSent) {
        userMessagesSent.push({sentBy: "user", content: messageSent});
        setUserMessage("");
        console.log(userMessagesSent)
    }
    return (
        <SafeAreaView style={styles.mainSafeAreaView}>
            <ScrollView style={styles.scrollArea}>
                {
                    userMessagesSent.map((item, index) =>
                        <SafeAreaView key={index} style={item.sentBy == "user" ? styles.userMessageAreaView : styles.botMessageAreaView}>
                            <Text key={index} style={item.sentBy == "user" ? styles.usersMessage : styles.botMessage}>{item.content}</Text>
                        </SafeAreaView>
                    )
                }
                </ScrollView>
            <SafeAreaView style={styles.bottomSafeAreaView}>
                <TextInput
                    value={userMessage}
                    style={styles.userMessageTextInput}
                    placeholder="Enter a message"
                    onChangeText={(text) => setUserMessage(text)}
                    onFocus={() => setFocused(true)}
                    onSubmitEditing={() => setFocused(false)}
                    onEndEditing={() => setFocused(false)}
                />
                <TouchableHighlight 
                    onPress={() => sendMessage(userMessage)}
                    underlayColor={'white'}
                >
                    <Image 
                        source={require(".././assets/send.png")}
                        style={styles.sendButton}
                        resizeMode='cover'
                    />
                </TouchableHighlight>
            </SafeAreaView>            
        </SafeAreaView> 
    );
}

export default ChatWindow;

I really have to complete the app fast, so if you could help me then it would be great.

CodePudding user response:

you're using a variable to store state. If you want the data to persist then you need to use useState(). Otherwise when the data changes your component wont re-render. Thats why you arent seeing the update. For more information on using variables vs state see this stack overflow question

const [userMessageSent, setUserMessageSent] = useState([
  {sentBy: "user", content: "Bursa will be the capital of ottoman"},
  {sentBy: "araf", content: "Agree"}
  ])
function sendMessage(messageSent) {
  setUserMessagesSent(prevState => ([...prevState, {sentBy: "user", content: messageSent}])
  setUserMessage("");
  }

CodePudding user response:

I think it has something to do with the way you save massages. Is there a specific reason why you are not saving your array with the messages in the state? Maybe that would fix your problem

  • Related