简体   繁体   中英

ReactJS / Axios / Firebase - Passing response data from POST to use in a PUT

I am using Axios.post to create a new record. With this new record there is a unique key assigned to this record from Firebase that I need in my next PUT operation.

Currently I'm using nested.then and it seems to be working as it should. I'm just unsure how I can convert this to a Promise.all without knowing the unique key to pass into my second query. It seems it's susceptible to problems the way I have it structured. Is there a way I can use Promise.all to ensure both queries executed? Or maybe it's fine as is?

Fully functioning sandbox is here: https://codesandbox.io/s/react-sample-5nc1z?file=/index.js

And here is the part in question:

  postColumn = (columnArr) => {
    axios
      .post(
        "/workflow/boards/" + this.state.boardID + "/columns.json",
        columnArr
      )
      .then((response) => {
        // console.log(response);
        const newColumnIds = [...this.state.columnIds, response.data.name];
        const newColState = {
          columns: {
            ...this.state.columns,
            [response.data.name]: { columnvalue: columnArr.columnvalue },
          },
        };
        this.setState(newColState);
        axios
          .put(
            "/workflow/boards/" + this.state.boardID + "/columnIds.json",
            newColumnIds
          )
          .then((response) => {
            const newColIdState = {
              columnIds: newColumnIds,
            };
            this.setState(newColIdState);
          })
          .catch((error) => {
            console.log("Error in putColumnIds", error);
          });
      })
      .catch((error) => {
        console.log("Error in postColumn", error);
      });
  };

If your second request is dependent on some data from your first request, Promise.all will not work. The purpose of Promise.all is to run two Promises (in your case, network requests) simultaneously, so if you are unable to do that (because you rely on one completing first, you cannot use it). That being said, your code looks totally fine and as long as it works, there should be nothing wrong with your implementation.

See more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

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