Home > Blockchain >  TypeError in React Native
TypeError in React Native

Time:09-22

I'm following a basic YouTube tutorial and following along I'm getting an error:

'TypeError: Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a Symbol.iterator method.'

I've checked multiple questions and answers, but I still can't get my head around why it's not working or an alternative solution.

export default function App() {

const [task, setTask] = useState();
const [taskItems, setTaskItems] = useState([]);

const handleAddTask = () => {
setTaskItems([...setTaskItems, task])
// console.log(task)
setTask(null)
}

return (
<View style={styles.container}>
  <View style={styles.tasksWrapper}>
    <Text style={styles.sectionTitle}>Today's Tasks</Text>
  

  <View style={styles.items}>
    {
      taskItems.map((item, index) => {
        return (
          <TouchableOpacity key={index}  onPress={() => handleAddTask(index)}>
            <Task text={item} /> 
          </TouchableOpacity>
        )
      })
    }
  </View>
  </View>

  <KeyboardAvoidingView 
    behavior={Platform.OS === "ios" ? "padding" : "height"}
    style={styles.writeTaskWrapper}
    >
      <TextInput style={styles.input} placeholder={'Write a task here'} value={task} onChangeText={text => setTask(text)} />
      <TouchableOpacity onPress={() => handleAddTask()} >
        <View style={styles.addWrapper}>
          <Text style={styles.addText}> </Text>
        </View>
      </TouchableOpacity>
    </KeyboardAvoidingView>
</View>
);}

The code I'm getting the error with is

setTaskItems([...setTaskItems, task])

Any help would be really appreciated! Thanks

CodePudding user response:

setTaskItems([...taskItems, task])

CodePudding user response:

You can't spread a function and setTaskItems is a function that sets the state of taskItems. Try doing

setTaskItems([...taskItems, task]) 

which I think is what you want to accomplish, to add the task into the existing taskItems array.

  • Related