Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

you can also try this as the array 'unshift' method does not return a modified array.

Clone the state first using the spread operator and then update the state.

function addItem(newTodo) {
  let arrayToUpdate = [...todos];
  arrayToUpdate.unshift(newTodo);
  setTodos(arrayToUpdate);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!