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’)
>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;