Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to save the axios.post request in a const and return that const in the function

export async function getCategories() {
  const https = "xxxxxx";
  const url = `${https}/api/Category/GetCategories`;

  const userToken ="xxxxxxxx"

  const authStr = "Bearer ".concat(userToken);

  const options = {
    method: "POST",
    headers: {
      Authorization: authStr,
    },
    url: url,
  };

  const response = await axios(options)
    .then((response) => console.log(response.data[0].categoryName))
    .catch((error) => console.log(error.toJSON()));

  const fetchedCategories = response.data[0];
  console.log(
    "🚀 ~ file: menu.js:27 ~ getCategories ~ fetchedCategories",
    fetchedCategories
  );

  return fetchedCategories;

when I
console.log(response) after setting
const FetchedCategories = response.data OR response.data[0].categoryId , since its an array I get this error in the terminal

WARN Possible Unhandled Promise Rejection (id: 4):
TypeError: undefined is not an object (evaluating ‘response.data’)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

.then returns undefined,.then((response) => console.log()), so then the response returned at const response = await axios(options) is also undefined, a better approach is to use try/catch as suggested in the other answer

export async function getCategories() {
  const https = "xxxxxx";
  const url = `${https}/api/Category/GetCategories`;

  const userToken ="xxxxxxxx"

  const authStr = "Bearer ".concat(userToken);

  const options = {
    method: "POST",
    headers: {
      Authorization: authStr,
    },
    url: url,
  };

  const response = await axios(options)
    // this returns undefined (response) => console.log()
    //.then((response) => console.log(response.data[0].categoryName))
    .catch((error) => console.log(error.toJSON()));

  const fetchedCategories = response.data[0];
  console.log(
    "🚀 ~ file: menu.js:27 ~ getCategories ~ fetchedCategories",
    fetchedCategories
  );

  return fetchedCategories;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading