简体   繁体   中英

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 []

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM