Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda