rumon
rumon

Reputation: 606

How to chain axios HTTP requests

I have 2 async await functions - one of them makes axios post request and another one - axios get request.

How could I chain them so that I would wait until the post operation is done and after it is completed, fetch new and updated objects?

const expensesListToDB = async () => {
    await axios.post('http://localhost:4000/app/expenseslist', 
    {
        expenseTitle: Expense,
        expenseAmount: Amount
    });
}

const expensesListFromDB = async () => {
    await axios.get('http://localhost:4000/app/expenseslist')
    .then(
    response => setExpenseAndAmountList(response.data && response.data.length > 0 ? response.data : []));
}

expensesListToDB();
expensesListFromDB();

Thanks!

Upvotes: 0

Views: 1635

Answers (3)

devAgam
devAgam

Reputation: 198

I suppose the API is in your control, the answers given by others are viable i would imagine a system where you return the new document in the response of the post request and just use it from their making it one single request

To have error handling and fault tolerance you could design your API response like this

{ "statusCode":"200",
  "event":"doc_added_successfully",
  "newDocs":{
  }

Upvotes: 1

DecPK
DecPK

Reputation: 25398

You can return Promise from expensesListToDB and in the .then block you can run the function expensesListFromDB

Once an HTTP POST request is made, Axios returns a promise that is either fulfilled or rejected, depending on the response from the backend service.

const expensesListToDB = () => {
  return axios.post("http://localhost:4000/app/expenseslist", {
    expenseTitle: Expense,
    expenseAmount: Amount,
  });
};

const expensesListFromDB = async () => {
  await axios
    .get("http://localhost:4000/app/expenseslist")
    .then((response) =>
      setExpenseAndAmountList(
        response.data && response.data.length > 0 ? response.data : []
      )
    );
};

expensesListToDB().then((data) => {
  expensesListFromDB();
});

Upvotes: 0

Ashutosh Jha
Ashutosh Jha

Reputation: 154

you can put expensesListFromDB() in the 'then' method of the Axios.

const expensesListToDB = async () => {
    await axios.post('http://localhost:4000/app/expenseslist', 
    {
        expenseTitle: Expense,
        expenseAmount: Amount
    }).then(
    response => expensesListFromDB()); }

const expensesListFromDB = async () => {
    await axios.get('http://localhost:4000/app/expenseslist')
    .then(
    response => setExpenseAndAmountList(response.data && response.data.length > 0 ? response.data : [])); }

expensesListToDB();

Upvotes: 1

Related Questions