Home > Back-end >  React Native To-Do app does not update state on click but does after another state updates
React Native To-Do app does not update state on click but does after another state updates

Time:10-07

I tried making a to-do app using React-native. It is a blank react native project that uses typescript and expo. I'm on linux.

The state containing the todo array gets updated it should but the view is not rendered accordingly untill I click the input button and change the text state.

I have 3 functions to modify the states - textChange (for updating the todoText state), handleAddTask (for updating the array containing tasks), rmTask ( removes item from task array)

  const [task, setTask] = useState('');
  const [taskItems, setTaskItems] = useState(["Write a task"]);

  const textChange = (text: string) => {
    setTask(text)
  }

  const handleAddTask = () => {
    taskItems.push(task)

    setTaskItems(taskItems)
    setTask('')
  }

  const rmTask = (index: number) => {
    taskItems.splice(index, 1);
    setTaskItems(taskItems)
  }

And the components where the functions are affecting

taskItems.map((item, index) => {
 return ( 
   <TouchableOpacity 
    key={index} 
    onPress={()=> rmTask(index)}
   >
  <Task text={item} />
 </TouchableOpacity>)
})

CodePudding user response:

const handleAddTask = () => {
  // taskItems.push(task) <-- Dont mutate state like this !

  setTaskItems([...taskItems, task]). <-- You should use it like this way.
  setTask('')
}

You are mutating the state value without using the setter function. Thats why Its not working correctly. And when you write something new to task input, UI gonna re-render and display the correct thing. Because textChange function implementation correct and update the state.

CodePudding user response:

In two places you are directly manipulating the state rather than using setState. You should do this way:

//taskItems.splice(index, 1);
//setTaskItems(taskItems)
// -should be
setTaskItems([...taskItems].splice(index, 1))

and

//taskItems.push(task)
//setTaskItems(taskItems)
// -should be
setTaskItems([...taskItems, task])
  • Related