4D.HTTPRequest issue

On init of a page I am executing a function to make an httprequest to to capture ISO country data from a website url and populate a qodlysource with the returned collection for viewing/testing for now.

I seem to be able to capture in a qodlysource and successfully display the returned collection of country data in the request response body when page loads no problem

However, when I add code to the function to loop through the returned country data collection and populate a new “countries” collection of country objects containing only the 2 pieces of data i need for each country, I get a really wierd result when the collection is displayed.

Wierd qodlysource result displayed:

The function code (note when i try to display simply the returned body of the request “rawcountries” i get a nice collection displayed as expected.)

exposed function getCountries():variant
	var requestoptions:object = newObject("method","GET")
	var request:4D.HTTPRequest
	request = 4D.HTTPRequest.new("https://restcountries.com/v3.1/all?fields=name,cca3",requestoptions)
	request.wait(2)
	var rawcountries:collection = request.response.body
	var rawcountry:object
	var countries:collection = newCollection()
	var country:object = newObject("name","","code","")

	forEach(rawcountry,rawcountries)
		country.name = rawcountry.name.common
		country.code = rawcountry.cca3
		countries.push(country)
	end

	return countries //note--returning rawcountries works fine as expected.

Thanks for any ideas…

Hello Robert,

This unexpected behavior is occurring due to the incorrect initialization of the country object, which is being reused and pushed multiple times into the returned collection. As a result, all entries in the collection end up referencing the same object.

To resolve this, you need to move the initialization of the country object inside the loop, so that a new object is created on each iteration.
Here’s the corrected code:

 exposed function getCountries() : collection
 	var requestoptions : object = newObject("method", "GET")
 	var request : 4D.HTTPRequest
 	request = 4D.HTTPRequest.new("https://restcountries.com/v3.1/all?fields=name,cca3", requestoptions)
 	request.wait(2)
 	var rawcountries : collection = request.response.body
 	var rawcountry, country : object
 	var countries : collection = newCollection()
 	
 	forEach (rawcountry, rawcountries)
 		country = newObject("name", "", "code", "") //move it in here
 		country.name = rawcountry.name.common
 		country.code = rawcountry.cca3
 		countries.push(country)
 	end 
 	
 	return countries  //note--returning rawcountries works fine as expected.

Let me know if that works for you!

1 Like

oops… Thanks for the help…Appreciated