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