0

I am working on a Gutenberg block and am modifying the Edit.js file. I want to fetch the root categories in the database. From the reading I have done, it seems a good way to do this is to use the REST API and perform a call like this:

var categories = fetch("http://localhost/wordpress_ttm/wp-json/wp/v2/categories")
                .then(response => response.json()) 

This all works fine and gives me back a response. Here is the structure of the response.

categories: Promise { "fulfilled" }
<state>: "fulfilled"
<value>: (10) […]
0: {…}
1: {…}
2: {…}
3: {…}
4: {…}
5: {…}
6: {…}
7: {…}
8: {…}
9: {…}
length: 10
<prototype>: []
<prototype>: Promise.prototype

How do I to get the data out of the response? I want to grab the array data and iterate over it, but I'm not sure how to do that.

1 Answer 1

1

fetch() is asynchronous so it returns a Promise -> you can’t access the data directly right after calling fetch(). In other words, you need to use .then() multiple times like this (this is called chaining):

fetch("http://localhost/wordpress_ttm/wp-json/wp/v2/categories")
  .then((response) => response.json()) // parse JSON
  .then((categories) => {
    console.log(categories); // now you can work with the array

    // Example loop
    categories.forEach((category) => {
      console.log(category.name);
    });
  })
  .catch((error) => {
    console.error("Error fetching categories:", error);
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.