Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

178
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda