I'm dealing with a JSON response that is coming from an API. The ResponseJson
contains information about a category; the responseJson.name
contains a category name (tested in the console). Now I want to add all category names and store them in the empty array, categoryNames
. After the for loop, the categoryNames
turns out to be empty when I try to print it in the console, and I'm not sure what I'm missing. Here is the code:
_getCategories = item => {
const categoryNames = [];
for (let category of item.categories) {
fetch('http://54.168.73.151/wp-json/wp/v2/categories/' + category)
.then(response => response.json())
.then(responseJson => {
var categoryName = responseJson.name;
categoryNames.push(categoryName);
})
.catch(error => {
this.setState({
isLoading: false,
isError: true,
});
console.error(error);
});
}
console.log(categoryNames);
};
This questions has been identified as a possible duplicate of another question, but the answers are the other question is about a $ajax call, while I am trying to use pure JavaScript. Are there any solutions with this syntax?