Home > front end >  Pushing to array removes old data (React Native)
Pushing to array removes old data (React Native)

Time:09-23

I'm trying to push text input into an array. When I modify the input text and push it, the array is wiped before the push (not showing my previous pushes in the console.log). What am I missing?

  const [text, onChangeText] = React.useState('Useless Text');

  let chatHistory = [];

  function logHistory(text) {
    chatHistory.push(text);
    console.log(chatHistory);
  }

  return (
    <View style={styles.container}>
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <TextInput
          style={styles.input}
          onChangeText={onChangeText}
          value={text}
        />
        <Button
          title={'Ask the computer...'}
          onPress={() => logHistory(text)}
        />
      </View>
    </View>
  );

CodePudding user response:

I supposed that because you change state, it rerender this component and redeclare chatHistory as empty array. use useState for chatHistory instead.

And instead of Array.push i recommend to use chatHistory = [...chatHistory, text],in useState case setChatHistory([...chatHistory,text]);

CodePudding user response:

If you want the changes in chatHistory to be reflected on your component you need to use a state and not just a plain variable. Such variables do not survive through re-renders and anything you store in regular variables will be lost. Try out after making these changes

  const [chatHistory, setChatHistory] = React.useState([]);

  function logHistory(text) {
    setChatHistory(history => [...history , text]);
  }

Also the console.log statement might not give you the result you are expecting. You might also want to display the chat history somewhere maybe in a flat list.

  • Related