0

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

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh, that's it! Thank you so much. The explanation really helped too so thank you for clarifying as well!
1
setTaskItems([...taskItems, task])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.