Gmaps API in beforeUpdate hook? Please help.

I don’t have a ton of experience coding, so apologies beforehand for anything super obvious or nonsensical.

I have a several user input fields on my Volunteer Signup page for users to sign up to volunteer. The information they submit is then used to create their personalized Volunteer Dashboard .

Two of the fields they fill out (street address and zip code) are used to populate the values of two other fields (houseDistrict & senateDistrict) that the user doesn’t have access to, but are required for their Volunteer Dashboard to function properly. Those values are determined using the Google Maps API and the OpenStates API that are intitaited by an onChange function.

The problem that I ran into is that if the last value the user enters before clicking submit is the field with the onChange function, it gets skipped. To work properly, the user needs to select something outside of that input field before clicking submit.

To work around that problem, I added the beforeUpdate hook to my VolunteerSignupForm database, then moved the Google Maps API and OpenStates API portion of the script to the data.js file located in the backend section.

Summary of Objective: I need to use the address field’s value in a series third party api’s to determine the value of two other fields before the submission makes it to the database.

I can’t figure out what I’m missing that is preventing those fields from now being updated. Here are the relevant sections of my code:

[ On my Volunteer page ]

export function button1_click() {
	var userId = wixUsers.currentUser.id;
	const toSave = {
		"_id": userId.toString(),
		"email": $w("#input3").value.toString(),
		"volunteerId": userId.toString(),
		"_owner": userId.toString(),
		"firstName": $w("#input1").value.toString(),
		"lastName": $w("#input2").value.toString(),
		"phone": $w("#input4").value.toString(),
		"streetAddress": $w("#input5").value.toString(),
		"zipCode": $w("#input6").value.toString(),
		"comments": $w("#textBox1").value.toString(),
		//"houseDistrict": $w("#input9").value,
		//"senateDistrict": $w("#input10").value
	};
	
	wixData.save("VolunteerSignupForm", toSave)
	.then( (results) => {
		let item = results;
		//console.log(results);
	} )
	.catch( (err) => {
		let errorMsg = err;
	} );
}

[data.js]

import {fetch} from "wix-fetch";

export function VolunteerSignupForm_beforeUpdate(item, context) {
	const url_G = "https://maps.googleapis.com/maps/api/geocode/json?address=";
	const key_G = "&key=1234567891011121314151617181920";
	const url_key_O = "https://openstates.org/api/v1/legislators/geo/?apikey=1111111-2222-3333-4444-55555555&lat=";

	let street = item.streetAddress;
	let zip = item.zipCode;
	console.log(street," ",zip);
	var fullUrl_G = url_G + street + " " + zip + key_G;

	fetch(fullUrl_G, {method: 'get'})
		.then(response => response.json())
		.then(json => {
			var lat = (JSON.stringify(json.results[0].geometry.location.lat) + "&long=");
			var lng = (JSON.stringify(json.results[0].geometry.location.lng));
			var fullUrl_O = (url_key_O + lat + lng);
			console.log(fullUrl_O);
			fetch(fullUrl_O, {method: 'get'})
				.then(answer => answer.json())
				.then(json2 => {
					var hd = ("House District " + ((JSON.stringify(json2[0].district)).replace('"', '')).replace('"', '')).toString();
					var sd = ("Senate District " + ((JSON.stringify(json2[1].district)).replace('"', '')).replace('"', '')).toString();
					item.setFieldValue("houseDistrict", hd);
					item.senateDistrict = sd;
					console.log(context);
				});
		});	

	return item;

}

Any suggestions would be appreciated!

Hey there,

Without looking into all the details of your code, I see at least one problem that could be causing your issue.

But, before getting to that, this forum is public. So you probably want to delete your API keys from your post.

Ok. You are doing two fetches, but returning the item outside the fetches. Since fetch is an asynchronous operation, the item will be returned before the fetches are even finished.

Good looking out on the API keys. Thanks Sam.

I tried to return the item as the last line of the second fetch but get the following console alert:

Hook beforeUpdate for collection VolunteerSignupForm result ignored! Expected hook result to resolve to an object with an ‘_id’ property, but got [Undefined]

Do I need to recompose the entire object within the fetch code? Its close to 40 properties that get assigned in the step prior to the hook being called?

Returning inside a then() of a promise does not do what you think. (I’m actually in the middle of writing an article about this. In the meantime…) Returning in the the then() resolves the promise. It does not return anything to the function. You want to return the promise itself. What that means for you is that you need to but a return before the fetch.

return fetch(....