Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
Pushing to array removes old data (React Native)

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>
);
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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]);

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!