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

165
Vistas
How to push data in the setState of array-type state?

I am having a state data. I wanted to push a new entry of the form

{  task:'ANy task',key:Math.random().toString() }

in the data array while using setData.

I had tried many ways mentioned here, but don't klnow why its not working.

Here's my code.

import React, { useState } from "react";
import { StyleSheet, Text, View, TextInput, Button } from "react-native";
import { StatusBar } from "expo-status-bar";

const Addtask = ({navigation}) => {
 
  const [data,setData] = useState([]);

  console.log("from add = ",data)

  const [task, setTask] = useState("");


  const handleSubmit = () => {
    console.log("submit pressed for task = ", task)
    

    const updatedData = [...data,{
      task:task,
      key: Math.random().toString(),
    }]
    //here i am setting the data
    setData(prevState => [...prevState,updatedData]);
    console.log("data after adding task",data)
    
    navigation.navigate("Tasklist",{data:data})
  }

  return (
    <View style={styles.container}>
      <StatusBar style="light" backgroundColor="midnightblue" />
      <View>
        <Text style={styles.text}>Add Task Here</Text>
      </View>

      <View>
        <TextInput
          style={styles.input}
          onChangeText={setTask}
          value={task}
          onChange={setTask}
          placeholder="Type your task"
          keyboardType="ascii-capable"
        />
      </View>

      <View style={styles.buttoms}>
        <View style={{margin:4}}>
          <Button color={'red'} onPress={()=>{navigation.goBack()}} title="Cancel"></Button>
        </View>
        <View style={{margin:4}}>
          <Button color={'lightblue'} onPress={()=>setTask('')} title="Clear"></Button>
        </View>
        <View style={{margin:4}}>
          <Button color={'green'} onPress={handleSubmit} title="Save"></Button>
        </View>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  .
  .
  .
});
export default Addtask;

To debug, I had used console stmts which reveals that the task value is coming in the handleSubmit() correctly but it is not getting pushed.

Log

submit pressed for task =  Morning bike ride.
data after adding task Array []
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Because You are already have

const updatedData = [...data,{
  task:task,
  key: Math.random().toString(),
}]

You don't need setData(prevState => [...prevState,updatedData]) you can just assign the updatedData to setData like setData(updatedData)

You can use

setData(current => [...current, {
  task:task,
  key: Math.random().toString(),
}])

Then you don't need updatedData

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