1

I have a file with form to call a submit function in another file. And I would like to retrieve the response of the request to use it in file 1. How can I do that ?

First file form.js

handleSubmit(event, user,props) {
event.preventDefault();
const nomAppartement = event.target.nomAppartement.value;
const superficieAppartement = event.target.superficieAppartement.value;

const newAppartementTableau = {
  nom: nomAppartement,
};

newAppartement(newAppartementTableau);
const messageRequest = ??;

Second file data.js

export function newAppartement(newAppartementTableau) {


axios({
    method: "post",
    url: urlAxiosAppartement,
    timeout: 1000 * 5, // Wait for 5 seconds
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + "****"
    },
    data: {
      fields: {
        nom: newAppartementTableau.nom
      }
    }
  })
    .then((response) => {
      return response;
    })
    .catch((err) => {
      return err;
    });
}

2 Answers2

1

You need to wait for the function to finish using await async:

async handleSubmit(event, user,props) {
  event.preventDefault();
  const nomAppartement = event.target.nomAppartement.value;
  const superficieAppartement = event.target.superficieAppartement.value;

  const newAppartementTableau = {
    nom: nomAppartement,
  };

  const response = await newAppartement(newAppartementTableau);

and in second file you can return a promise like this:

export function newAppartement(newAppartementTableau) {


return axios({
    method: "post",
    url: urlAxiosAppartement,
    timeout: 1000 * 5, // Wait for 5 seconds
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + "****"
    },
    data: {
      fields: {
        nom: newAppartementTableau.nom
      }
    }
  })
    .then((response) => {
      return response;
    })
    .catch((err) => {
      return err;
    });
}
Osama Bin Saleem
  • 779
  • 1
  • 12
  • 24
1

You are not returning anything in your function, you're just making an axios call. To solve this add this :

export function newAppartement(newAppartementTableau) {


return axios({
    method: "post",
    url: urlAxiosAppartement,
    timeout: 1000 * 5, // Wait for 5 seconds
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + "****"
    },
    data: {
      fields: {
        nom: newAppartementTableau.nom
      }
    }
  })
    .then((response) => {
      return response;
    })
    .catch((err) => {
      return err;
    });
}

in your first file

newAppartement(newAppartementTableau).then(res => console.log(res.data).catch(e => console.error(e));
kevin
  • 872
  • 5
  • 18