Reputation: 23
Almost a similar question was asked earlier but I could't figure it out in my case so here it is (I'm using react-native and expo):
I was using chrome to see the result of my codes for a to-do app and it was working well until I wanted to try it in my phone that I faced this once the "addTodo" function was called:
TypeError: null is not an object (evaluating 'arr.push')
this is the code:
addTodo = () => {
var newTodo = this.state.text;
var arr = this.state.todo;
if (!newTodo) {
alert("Empty!");
} else {
arr.push(newTodo);
this.setState({ todo: arr, text: "" });
this.setDataLocally();
}
"text" contains the string coming from the input and will be added to "todo" array.
as you can see the "arr.push" should only be called when "newTodo" is not null or empty.
I only get the error when I want to use the Asyncstorage. this is the what should be called at the end of above code:
setDataLocally = () => {
var jsonData = JSON.stringify(this.state.todo);
AsyncStorage.setItem("list", jsonData);
What should I do? thanks in advance!
Upvotes: 2
Views: 2240
Reputation: 121
The problem is that your variable is null .. but it expects a list.
Try this:
addTodo = () => {
var newTodo = this.state.text;
var arr = this.state.todo !== null ? this.state.todo : [];
if (!newTodo) {
alert("Empty!");
} else {
arr.push(newTodo);
this.setState({ todo: arr, text: "" });
this.setDataLocally();
}
Upvotes: 1