How to fetch data from specific groups on a board?

If I have this code below to fetch data from the Monday API from a specific board ID XXXX180027 and then passes the fetched data to an autocomplete function, how would I alter it so it only fetches data from the groups on this board with ids: topics, new_group34305 and new_group67377?

var allHospitalNames = [];

function fetchData() {
		    // Define your API key and board ID
		    const apiKey = 'MY_API_KEY';
		    const boardId = 'XXXX180027';

		    //create an empty clients object to store the data returned from Monday: 
		    var clients = {};

		    //set up a query to the api and fetch the needed data
			
		    let query = 
		        query {
		          boards(ids: ${boardId}) {
		            items_page(limit: 500) {
		              cursor
		              items {
		                id
		                name
		                column_values {
		                  column {
		                    title
		                  }
		                  text
		                  value
		                }
		              }
		            }
		          }
		        }
		    ;

		    return fetch("https://api.monday.com/v2", {
		        method: 'post',
		        headers: {
		            'Content-Type': 'application/json',
		            'Authorization': apiKey
		        },
		        body: JSON.stringify({
		            'query': query
		        })
		    })
		    .then(response => response.json())
		    .then(data => {
		        // Process the fetched data
		        const items = data.data.boards[0].items_page.items;
		        items.forEach(item => {
		            let hospitalName;
		            let websiteText;
		            let clinicLocation;
					let hospitalPhone;

		            hospitalName = item.name;
		            allHospitalNames.push(hospitalName);

		            item.column_values.forEach(columnValue => {
		                if (columnValue.column.title === "Website") {
		                    websiteText = columnValue.text;
		                }

		                if (columnValue.column.title === "Address (Text)") {
		                    clinicLocation = columnValue.text;
		                }
						
						if (columnValue.column.title === "Primary Contact Phone") {
		                    hospitalPhone = columnValue.text;
		                }
		            });

		            clients[hospitalName] = {
		                website: websiteText,
		                address: clinicLocation,
						phone: hospitalPhone
		            };
		        });

		        return clients;
		    })
		    .catch(error => {
		        console.error('Error fetching data:', error);
		        throw error; // Re-throw the error to be caught by the caller
		    });
		}

		//lets call the fetch to get all clients and their data from Monday: 

		fetchData()
	    .then(theClients => {
	        console.log(theClients);

	    	//now you need to run your autofill code inside this block

	   		autocomplete(document.getElementById("input_32_254"), allHospitalNames, theClients);

	   		//console.log(allHospitalNames);

	   		//now a function to check the Hospital Name field for a selection, once a selection is made by the user
	        //we then need to query the theClients object for its Website URL and fill that field with the value

	    })
	    .catch(error => {
	        console.error('Error:', error);
	    });

I’ve tried to modify my code so that it only fetches data from specific groups (topics, new_group34305, and new_group67377). I adjusted the GraphQL query to include a filter for the group IDs:

var allHospitalNames = [];

function fetchData() {
    // Define your API key and board ID
    const apiKey = 'MY_API_KEY';
    const boardId = 'XXXX180027';
    const groupIds = ['topics', 'new_group34305', 'new_group67377'];

    // Create an empty clients object to store the data returned from Monday
    var clients = {};

    // Set up a query to the API and fetch the needed data
    let query = `
        query {
          boards(ids: ${boardId}) {
            groups(ids: ${groupIds.map(id => `"${id}"`).join(',')}) {
              items {
                id
                name
                column_values {
                  column {
                    title
                  }
                  text
                  value
                }
              }
            }
          }
        }
    `;

    return fetch("https://api.monday.com/v2", {
        method: 'post',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': apiKey
        },
        body: JSON.stringify({
            'query': query
        })
    })
    .then(response => response.json())
    .then(data => {
        // Process the fetched data
        const groups = data.data.boards[0].groups;
        groups.forEach(group => {
            group.items.forEach(item => {
                let hospitalName;
                let websiteText;
                let clinicLocation;
                let hospitalPhone;

                hospitalName = item.name;
                allHospitalNames.push(hospitalName);

                item.column_values.forEach(columnValue => {
                    if (columnValue.column.title === "Website") {
                        websiteText = columnValue.text;
                    }

                    if (columnValue.column.title === "Address (Text)") {
                        clinicLocation = columnValue.text;
                    }
                    
                    if (columnValue.column.title === "Primary Contact Phone") {
                        hospitalPhone = columnValue.text;
                    }
                });

                clients[hospitalName] = {
                    website: websiteText,
                    address: clinicLocation,
                    phone: hospitalPhone
                };
            });
        });

        return clients;
    })
    .catch(error => {
        console.error('Error fetching data:', error);
        throw error; // Re-throw the error to be caught by the caller
    });
}

// Let's call the fetch to get all clients and their data from Monday
fetchData()
    .then(theClients => {
        console.log(theClients);

        // Now you need to run your autofill code inside this block
        autocomplete(document.getElementById("input_32_254"), allHospitalNames, theClients);

        // Now a function to check the Hospital Name field for a selection, once a selection is made by the user
        // we then need to query the theClients object for its Website URL and fill that field with the value

    })
    .catch(error => {
        console.error('Error:', error);
    });

But I’m getting an error in the browser console:

Error fetching data: TypeError: data.data is undefined
    fetchData https://stg-XXX-stagingalex.kinsta.cloud/support/:2943
    promise callback*fetchData https://stg-ivet360alex-stagingalex.kinsta.cloud/support/:2941
    <anonymous> https://stg-XXX-stagingalex.kinsta.cloud/support/:2985
    jQuery 9
        dispatch
        handle
        add
        ke
        each
        each
        ke
        on
        bind
    <anonymous> https://stg-XXX-stagingalex.kinsta.cloud/wp-content/themes/blankslate/js/scripts.js?ver=6.5.5:2958

Any help here would be greatly appreciated!!

This would be because there is a graphql error and the data object is not being returned. See the article below for all of the ways the API currently returns graphql errors (many are not currently spec compliant but in API 2024-10 they intend to always return a spec compliant error).

You need to check for the presence of errors, error_code, and error_message keys to log out the errors for handling or trouble shooting.

Or just log out the entire response in the absence of a data object (which may not always be true so long term do not rely on that to tell you there is an error) in the short term. (during development).

I realize that. I’m really just wondering how to fetch data from specific groups. Obviously the way I’m doing it is not correct, so its throwing an error. Is there any documentation or guidance for fetching data from specific groups on a board? My code works until I try to fetch specific groups from the board.

This query works to return data from the board:

			
		    let query = 
		        query {
		          boards(ids: ${boardId}) {
		            items_page(limit: 500) {
		              cursor
		              items {
		                id
		                name
		                column_values {
		                  column {
		                    title
		                  }
		                  text
		                  value
		                }
		              }
		            }
		          }
		        }
		    ;

However, I’ve tried:

let query = `
        query {
          boards(ids: ${boardId}) {
            groups(ids: ${groupIds.map(id => `"${id}"`).join(',')}) {
              items {
                id
                name
                column_values {
                  column {
                    title
                  }
                  text
                  value
                }
              }
            }
          }
        }
    `;

I’ve also tried:

let query = `
        query {
          boards(ids: ${boardId}) {
            items_page(limit: 500, group_ids: ${JSON.stringify(groupIds)}) {
              cursor
              items {
                id
                name
                column_values {
                  column {
                    title
                  }
                  text
                  value
                }
              }
            }
          }
        }
    `;

Hi @adouglas_ivet,

You can no longer query items on groups, so you have to use items_page. Check out the docs here and let me know if this helps :smiley:

Best,
Rachel

Yes, the reason I said to check your errors is it would tell you the issue - items doesn’t exist on groups. (you have to use items_page within groups).

I highly recommend debugging your queries in the GraphQL API Playground of the dev center in your dev account. You can see responses, and since it has the schema it can help you write proper queries.

You can also of course set up your dev environment tooling to use the monday.com GraphQL schema so you get auto-completion in your IDE that conforms to the schema.

1 Like