2

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!

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.