0

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>)
})
ImtiazKun
  • 15
  • 4
  • You are not currently updating state values. See [Correct modification of state arrays in React.js](https://stackoverflow.com/questions/62918710/how-to-update-state-with-usestate-in-an-array-of-objects) – Shivam Jha Oct 06 '21 at 17:50

2 Answers2

1
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.

Bariscode
  • 160
  • 2
  • 4
0

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])
ABDULLOKH MUKHAMMADJONOV
  • 4,249
  • 3
  • 22
  • 40