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?
CodePudding user response:
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.
CodePudding user response:
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);
}