Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

155
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda