Comments (9)
@tsheaff your solution looks great 🙌 I think we will build queuing mechanism for our npm package in near future as well so you don't have to wrap the library/import internal types
from analytics-next.
Ah OK great. I'll keep track of this issue until that's done. Can you leave this open and track that PR against this issue? I've renamed it for more clarity.
from analytics-next.
@tsheaff this is an awesome suggestion! We're actively working on this feature, I will tag you in the PR.
from analytics-next.
Feature merged in #436, should be available next release.
from analytics-next.
@tsheaff The npm version (unlike the CDN/snippet based solution) requires you to implement queuing yourself. Although the implementation should be straightforward. Can you check the response on this issue and see if that solves your issue: #374
from analytics-next.
Ah OK thanks for the fast reply @pooyaj!
That's unfortunate. I did see that queueing in the snippet. Unfortunately that doesn't work in Typescript. It seems like this could be built into the library. For example:
const [analytics] = AnalyticsBrowser.configure(...); // same options as `.load(...)`
await analytics.load();
Then analytics.track(...)
etc can all work instantly, with the queueing behavior being something that moves inside the library and then is flushed when .load()
finished. So loaded vs not is transparent to the caller.
Here's a solution that works for just 3 of the methods on analytics
objects, but is fully typesafe. It does require importing from within the package tho. A sanity-check would be fantastic @pooyaj 🙏
import { Analytics, AnalyticsBrowser } from '@segment/analytics-next';
import { EventParams, PageParams, UserParams } from '@segment/analytics-next/dist/pkg/core/arguments-resolver';
type EnqueuedSegmentCall =
{
type: 'track';
args: EventParams;
} |
{
type: 'page';
args: PageParams;
} |
{
type: 'identify';
args: UserParams;
};
class Analytics {
private analytics: Analytics | undefined;
constructor() {
this.load();
}
private async load() {
const writeKey = process.env.REACT_APP_SEGMENT_WRITE_KEY;
const cdnURL = process.env.REACT_APP_SEGMENT_CDN_PROXY;
if (!writeKey) throw new Error('Segment Write Key Cannot Be Undefined');
if (!cdnURL) throw new Error('Segment CDN URL Cannot Be Undefined');
const [analytics] = await AnalyticsBrowser.load({ writeKey, cdnURL });
this.analytics = analytics;
this.flushQueue();
}
private enqueuedCalls: EnqueuedSegmentCall[] = [];
private flushQueue() {
this.enqueuedCalls.forEach((call) => {
switch (call.type) {
case 'track':
return this.track(...call.args);
case 'page':
return this.page(...call.args);
case 'identify':
return this.identify(...call.args);
}
});
this.enqueuedCalls = [];
}
track(...args: EventParams) {
if (!this.analytics) {
this.enqueuedCalls.push({ type: 'track', args: args });
return;
}
this.analytics.track(...args);
}
page(...args: PageParams) {
if (!this.analytics) {
this.enqueuedCalls.push({ type: 'page', args: args });
return;
}
this.analytics?.page(...args);
}
identify(...args: UserParams) {
if (!this.analytics) {
this.enqueuedCalls.push({ type: 'identify', args: args });
return;
}
this.analytics?.identify(...args);
}
}
export default new Analytics();
This then gives us this very clean interface throughout our calling code:
import analytics from '@analytics/analytics';
analytics.track(...);
analytics.page(...);
analytics.identify(...);
from analytics-next.
I think it will require a new interface as I mentioned as well so that you can get your analytics
instance without any await
from analytics-next.
Released in https://github.com/segmentio/analytics-next/releases/tag/v1.38.0
from analytics-next.
Thank you so much for implementing this! You saved us a ton of work! It worked great!
from analytics-next.
Related Issues (20)
- Amplitude Integration not loading correctly HOT 1
- Blink display on loading segment library HOT 2
- Provide visibility to errors if segment events do not send
- Rename @segment/analytics-node to @segment/analytics-javascript HOT 3
- Rare Context2 in Nuxt 3 HOT 1
- Can not install library without node overrides HOT 5
- Consent module pollutes logs when using OneTrust's "Consent Rate Optimization" feature. HOT 1
- Can `.load()` support a symmetric key to not expose real write key? HOT 1
- analytics-node does not close HTTPS connection on closeAndFlush HOT 2
- Snippet version 5.2.0 loads analytics.min.js and analytics.classic.js at the same time HOT 1
- How to Set a Whitelist of Domains for a Segment JavaScript source WriteKey to Prevent Misuse? HOT 1
- Typescript issue on consent object of CoreExtraContext type HOT 1
- Analytics not flushed in Node >= 18 HOT 1
- Safari's Enhanced Tracking Protection Leads to Unhandled Promise Rejection HOT 11
- @segment/analytics-consent-wrapper-onetrust README code sandbox link looks incorrect HOT 1
- npm install fails for Node 18.XX and Node 20.XX HOT 1
- Cannot install package via NPM HOT 7
- Could not resolve "./lib/window-analytics-helper" when building with vite HOT 1
- Setting a low `flushInterval` effectively breaks `closeAndFlush()` HOT 2
- analytics.user function should be listed as optionally undefined in typescript definitions HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from analytics-next.