Home > Software design >  Correct Async/Await usage with Axios
Correct Async/Await usage with Axios

Time:08-11

I'm working with axios to post user responses to a database. I'm using this set up shown below to handle many posts back to back. I'm wanting to make sure that this is the correct set up to avoid backing up requests.

Is this the correct way to use async and await when using Axios?

// Frontend React Code
// Posting conclusionInput to Mongodb
const postConclusion = async () => {
  await axios({
    method: "POST",
    data: {
      conclusion: conclusionInput,
    },
    withCredentials: true,
    url: "http://localhost:4000/conclusion",
  }).then((res) => console.log(res));
};

//Backend Node / Express code
app.post("/conclusion", (req, res) => {
  console.log("Attempting to post the conclusion");
  User.findOne({ username: req.user.username }, async (err, user) => {
    if (err) throw err;
    if (user) {
      (user.conclusion = req.body.conclusion), await user.save();
      res.send();
    }
  });
});

CodePudding user response:

I recommended have a folder called "services" and inside it has yours services by backend.

services/ getData.js

import axios from "axios";

export const getData = () => {
  axios.post("http://localhost:4000/conclusion");
};

App.js

import { useEffect, useState } from "react";
import { getData } from "./services/getData";

export default function App() {
  const [data, setData] = useState([]); // save the value of service
  useEffect(() => {
    try {
      getData().then((res) => {
        setData(res?.data);
      });
    } catch (e) {
      console.error(e);
    }
  }, []); // execute once
  return <div className="App">{data}</div>;
}

CodePudding user response:

When using async await, setting an await call to a variable is equal to the parameter in a .then callback

// Frontend React Code
// Posting conclusionInput to Mongodb
const postConclusion = async () => {
 // Set the await call to a variable. 
  const res = await axios({
    method: "POST",
    data: {
      conclusion: conclusionInput,
    },
    withCredentials: true,
    url: "http://localhost:4000/conclusion",
  })
 // Now no need for .then()!! This is why async/await is so nice. 
 console.log(res)
};

//Backend Node / Express code
app.post("/conclusion", (req, res) => {
  console.log("Attempting to post the conclusion");
  User.findOne({ username: req.user.username }, async (err, user) => {
    // You need to send the error to the request. Otherwise, the 
    // request will keep waiting for a response until it times out.
    if (err) {
      console.error(err)
      res.status(500).send(err)
    }
    if (user) {
      // Side note: these should all be on separate lines:
      user.conclusion = req.body.conclusion
      await user.save();
      // You should also send a status code and a response message
      res.status(200).send({status: "Success}");
    }
  });
});
  • Related