Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

todos.unshift is not a function

When I try to add to the beginning of an array in React Native I get the following error:

TypeError: todos.unshift is not a function. (In 'todos.unshift(newTodo)', 'todos.unshift' is undefined)

My Code is :

export default function App() {
  const [todos, setTodos] = useState(['Hello']);
  const [todo, setTodo] = useState('');

  function addItem(newTodo) {
    console.log(newTodo);
    setTodos(todos.unshift(newTodo));
  }

  return (
    <TouchableWithoutFeedback
      onPress={() => {
        Keyboard.dismiss();
      }}
    >
      <View style={styles.container}>
        <TextInput
          placeholder='new todo'
          style={styles.input}
          value={todo}
          onChangeText={(text) => {
            setTodo(text);
          }}
        ></TextInput>
        <Button title='Add' onPress={()=>addItem(todo)}></Button>
      </View>
    </TouchableWithoutFeedback>
  );
}

Why is this happening . Is useState not applying the type of todos as an array?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

method ‘unshift’ does not return modified array. you can see how it works here.

and mutating state without setState method is not recommend because in that case React cannot detect the change.

you can use setTodos(arr => [newTodo, ...arr]) instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading