在两次Axios调用后如何设置SetState?

时间:2018-07-11 11:00:01

标签: javascript reactjs django-models axios

我可能做错了,但是我需要打两个Axios电话。一种是使用Django从我的数据库中检索数据,该数据库存储API信息,另一种是使用该API密钥调用Google日历。

这两个调用都可以,但是返回响应会导致setState不设置来自Google日历的调用值。呼叫依赖于第一次呼叫的第二次呼叫的最佳方法是什么?

ComponentDidMount

componentDidMount() {
   this.getGCalCredentials();

};

getGCALCredentials:

axios.defaults.withCredentials = true;
    var url;
    const apiBaseUrl = "http://localhost:8000/";
    const payload = {
        "APIKey": this.state.APIKey,
        "CalendarID": this.state.CalendarID
    };
    axios.defaults.xsrfCookieName = 'csrftoken';
    axios.defaults.xsrfHeaderName = 'X-CSRFToken';
    const localEvent = [];
     axios.get(apiBaseUrl + 'api/GetGCALCredentials/', payload, { headers: {'Accept': 'application/json'} }).then ( (response)  => {
        if (response.status == 200) {
            console.log("Successful. Credentials.");
            const d = JSON.parse(response.data);
            url = `https://www.googleapis.com/calendar/v3/calendars/` + d[0].fields.CalendarID + `/events?key=` + d[0].fields.APIKey + ``;
            this.setState({APIKey: d[0].fields.APIKey, CalendarID: d[0].fields.CalendarID});
            this.setState({url: url});
            console.log("[GCALCredentials] State is set:" + this.state.toString());
        }
        else if (response.status == 204) {
            console.log("Other Error");
            alert("username password do not match")
        }
        else if (response.status == 400) {
            console.log("Did not save successfully. ");
            alert("Did not save successfully. ")
        }
        else {
            console.log("Another error");
            alert("Some other Error.");
        }
        })
     .catch(function (error) {
            if (error.response.status==400){
                alert("Check your credentials at arlo.netgear.com. Invalid email or password. ");
                console.log("Data:" + error.response.data);
                console.log("Status: " + error.response.status);
                console.log("Headers: " + error.response.headers);
                console.log("Error: "+ error);
            }
     })
     .then(function(){
         axios.get(url)
          .then(function (resp) {
                resp.data.items.map((i) => {
                  const start = moment(i.start.dateTime, 'YYYY-MM-DD HH:mm').toDate();
                  const end = moment(i.start.dateTime, 'YYYY-MM-DD HH:mm').toDate();
                  localEvent.push({
                      fromDate: start,
                      toDate: end,
                      summary: i.summary,
                  });

              });
          })
          .then( (response) => {
              this.setState({events: localEvent});
              console.log("Google Calendar. State:" + this.state.toString());
         })
          .catch(function (error) {
              console.log(error);
          });
      })

0 个答案:

没有答案