11import { Action } from '@reduxjs/toolkit'
2- import { onLogOut , onRehydrationComplete } from 'store/app'
2+ import { onForeground , onLogOut , onRehydrationComplete } from 'store/app'
33import { selectDistinctID } from 'store/posthog'
44import { AppListenerEffectAPI , AppStartListening } from 'store/types'
5- import Branch from 'react-native-branch'
5+ import Branch , { BranchEvent } from 'react-native-branch'
6+ import Logger from 'utils/Logger'
67
78export const addBranchListeners = ( startListening : AppStartListening ) : void => {
8- const branchIdentifyUser = (
9+ const branchIdentifyUser = async (
910 _ : Action ,
1011 listenerApi : AppListenerEffectAPI
11- ) : void => {
12+ ) : Promise < void > => {
1213 const distinctId = selectDistinctID ( listenerApi . getState ( ) )
1314 Branch . setIdentity ( distinctId )
1415 Branch . setRequestMetadata ( '$posthog_distinct_id' , distinctId )
16+ createBranchOpenedEvent ( distinctId )
17+ }
18+
19+ const onCreatedBranchOpenedEvent = async (
20+ _ : Action ,
21+ listenerApi : AppListenerEffectAPI
22+ ) : Promise < void > => {
23+ const distinctId = selectDistinctID ( listenerApi . getState ( ) )
24+ Branch . setRequestMetadata ( '$posthog_distinct_id' , distinctId )
25+ createBranchOpenedEvent ( distinctId )
26+ }
27+
28+ const createBranchOpenedEvent = async ( distinctId : string ) : Promise < void > => {
29+ const branchUniversalObject = await Branch . createBranchUniversalObject (
30+ 'app_opened' ,
31+ { }
32+ )
33+ const params = {
34+ customData : { posthog_distinct_id : distinctId }
35+ }
36+
37+ const event = new BranchEvent ( 'app_opened' , [ branchUniversalObject ] , params )
38+ event
39+ . logEvent ( )
40+ . then ( ( ) => {
41+ Logger . info ( 'branch custom event [app_opened] logged successfully' )
42+ } )
43+ . catch ( error => {
44+ Logger . error ( 'branch custom event [app_opened] logging failed' , error )
45+ } )
1546 }
1647
1748 const branchLogout = ( _ : Action , __ : AppListenerEffectAPI ) : void => {
@@ -27,4 +58,9 @@ export const addBranchListeners = (startListening: AppStartListening): void => {
2758 actionCreator : onLogOut ,
2859 effect : branchLogout
2960 } )
61+
62+ startListening ( {
63+ actionCreator : onForeground ,
64+ effect : onCreatedBranchOpenedEvent
65+ } )
3066}
0 commit comments