diff --git a/src/ga4.js b/src/ga4.js index cf6a597..9ebf41e 100644 --- a/src/ga4.js +++ b/src/ga4.js @@ -216,14 +216,14 @@ export class GA4 { } }; - set = (fieldsObject) => { + set = (fieldsObject, args = null) => { if (!fieldsObject) { console.warn("`fieldsObject` is required in .set()"); return; } - if (typeof fieldsObject !== "object") { + if (typeof fieldsObject !== "object" && !args) { console.warn("Expected `fieldsObject` arg to be an Object"); return; @@ -233,7 +233,7 @@ export class GA4 { console.warn("empty `fieldsObject` given to .set()"); } - this._gaCommand("set", fieldsObject); + this._gaCommand("set", fieldsObject, args); }; _gaCommandSendEvent = ( @@ -347,10 +347,17 @@ export class GA4 { }; _gaCommandSet = (...args) => { - if (typeof args[0] === "string") { - args[0] = { [args[0]]: args[1] }; + const newArgs = []; + + if (typeof args[0] === 'string' && typeof args[1] === 'object') { + newArgs.push(args[0], args[1]) + } else if (typeof args[0] === "string") { + newArgs.push(this._toGtagOptions({ [args[0]]: args[1] })) + } else { + newArgs.push(this._toGtagOptions(args[0])) } - this._gtag("set", this._toGtagOptions(args[0])); + + this._gtag("set", ...newArgs); }; _gaCommand = (command, ...args) => { diff --git a/src/ga4.test.js b/src/ga4.test.js index a9042d5..b955ba8 100644 --- a/src/ga4.test.js +++ b/src/ga4.test.js @@ -279,6 +279,25 @@ describe("GA4", () => { page_path: "/home", }); }); + + it("set() with additional params", () => { + // Given + const object = ['user_properties', { + favorite_composer: 'Mahler', + favorite_instrument: 'double bass', + season_ticketholder: 'true' + }]; + + // When + GA4.set(...object); + + // Then + expect(gtag).toHaveBeenNthCalledWith(1, "set", "user_properties", { + favorite_composer: 'Mahler', + favorite_instrument: 'double bass', + season_ticketholder: 'true' + }); + }); }); describe("Reference", () => {