@@ -155,16 +155,54 @@ function Content() {
155155 // Reset user info in the sign-out logic instead.
156156 } , [ isLoaded , postHog , user ] ) ;
157157
158+ /**
159+ * The `useEffect` below sets the PostHog group properties based on:
160+ *
161+ * 1. If `currentTenant` is available, since it contains rich data, set the group with both ID
162+ * and necessary properties.
163+ * 2. If only `currentTenantId` is available, set the group with only ID. This usually happens
164+ * when the URL contains a tenant ID but the tenant data is not loaded yet or the tenant is
165+ * unavailable to the user.
166+ * 3. If neither is available, reset all group properties. This usually happens when the user is
167+ * not in a tenant context.
168+ *
169+ * @caveat
170+ * We need to identify group when window is reactivated (tab switch or window switch)
171+ * since one user may access different tenants in different tabs or windows.
172+ *
173+ * Currently, PostHog DOES capture the correct group when the user switches tabs or windows
174+ * since it reads the properties from the memory if existing, but just in case it doesn't work
175+ * in the future, we add this logic here.
176+ *
177+ * See {https://github.com/PostHog/posthog-js/blob/b5eb605/packages/core/src/posthog-core-stateless.ts#L778-L783 | posthog-js source code}
178+ * for details at the time of writing.
179+ */
158180 useEffect ( ( ) => {
159- if ( currentTenant ) {
160- postHog . group ( 'tenant' , currentTenantId , {
161- name : currentTenant . name ,
162- } ) ;
163- } else if ( currentTenantId ) {
164- postHog . group ( 'tenant' , currentTenantId ) ;
165- } else {
166- postHog . resetGroups ( ) ;
167- }
181+ const captureGroups = ( ) => {
182+ if ( currentTenant ) {
183+ postHog . group ( 'tenant' , currentTenantId , {
184+ name : currentTenant . name ,
185+ } ) ;
186+ } else if ( currentTenantId ) {
187+ postHog . group ( 'tenant' , currentTenantId ) ;
188+ } else {
189+ postHog . resetGroups ( ) ;
190+ }
191+ } ;
192+
193+ captureGroups ( ) ;
194+
195+ const handleVisibilityChange = ( ) => {
196+ if ( document . visibilityState === 'visible' ) {
197+ captureGroups ( ) ;
198+ }
199+ } ;
200+
201+ document . addEventListener ( 'visibilitychange' , handleVisibilityChange ) ;
202+
203+ return ( ) => {
204+ document . removeEventListener ( 'visibilitychange' , handleVisibilityChange ) ;
205+ } ;
168206 } , [ postHog , currentTenantId , currentTenant ] ) ;
169207
170208 /**
0 commit comments