简体   繁体   中英

Get response from data api in react native using axios

I'm new to react-native and javascript. In my code I try to get some response using axios, when I try to add the array (this.state.toDoList.push). it never called. why is this happening?

addNote() {
    const {state} = this.props.navigation;
    axios.post('https://ngc-todo.herokuapp.com/api/tasks', {
        userId: state.params.user,
        status: this.state.done,
        task: this.state.toDoInput,
        dueDate: this.state.dueDate,
        category:this.state.selectCate
    }).then(function(response) {
        console.log(response)
        return response.data; 
        if (response.data.success == true) {
            () =>  this.state.toDoList.push({
                    taskId:response.data.data._id,
                    note: this.state.toDoInput,
                    date: this.state.dueDate, 
                    status: this.state.done,
                    category: this.state.selectCate               
                });
            console.log(this.state.toDoList)
            this.setState({ toDoList: this.state.toDoList });
         } else {
               Alert.alert(response.data.message)
         }
    });
}

It's never called because of the line: return response.data; also change this line .then(function (response) { as in the example below:

 .......
         .then((response) => {
            console.log(response)
            return response.data; //comment this line
            if (response.data.success == true) { 
               this.state.toDoList.push({
                  taskId:response.data.data._id,
                  ...............
                  ............ 
               });

In this code:

if (response.data.success == true) {
  () =>  this.state.toDoList.push({
    taskId:response.data.data._id,
    note: this.state.toDoInput,
    date: this.state.dueDate, 
    status: this.state.done,
    category: this.state.selectCate               
  });
  console.log(this.state.toDoList)
  this.setState({ toDoList: this.state.toDoList });
}

...you are defining an arrow function for some reason rather than actually calling .push directly. Also, it's not advisable to mutate the array rather than passing a new array. Try this instead:

if (response.data.success) {
  this.setState({ 
    toDoList: this.state.toDoList.concat([
      {
        taskId:response.data.data._id,
        note: this.state.toDoInput,
        date: this.state.dueDate, 
        status: this.state.done,
        category: this.state.selectCate               
      }
    ]) 
  }, () => console.log(this.state.toDoList));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM