@kameleoon/react-sdk 5.0.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/README.md +62 -1456
  2. package/dist/KameleoonContext.d.ts +2 -2
  3. package/dist/KameleoonContext.js.map +1 -1
  4. package/dist/KameleoonError.d.ts +1 -1
  5. package/dist/KameleoonProvider.d.ts +5 -5
  6. package/dist/KameleoonProvider.js +1 -1
  7. package/dist/KameleoonProvider.js.map +1 -1
  8. package/dist/constants.d.ts +1 -24
  9. package/dist/constants.js +2 -28
  10. package/dist/constants.js.map +1 -1
  11. package/dist/eventSource/browserEventSource.d.ts +4 -0
  12. package/dist/eventSource/browserEventSource.js +38 -0
  13. package/dist/eventSource/browserEventSource.js.map +1 -0
  14. package/dist/eventSource/index.d.ts +2 -0
  15. package/dist/eventSource/index.js +8 -0
  16. package/dist/eventSource/index.js.map +1 -0
  17. package/dist/eventSource/nativeEventSource.d.ts +4 -0
  18. package/dist/eventSource/nativeEventSource.js +39 -0
  19. package/dist/eventSource/nativeEventSource.js.map +1 -0
  20. package/dist/index.d.ts +16 -42
  21. package/dist/index.js +34 -92
  22. package/dist/index.js.map +1 -1
  23. package/dist/kameleoonClient.d.ts +4 -13
  24. package/dist/kameleoonClient.js +18 -72
  25. package/dist/kameleoonClient.js.map +1 -1
  26. package/dist/kameleoonUtils/browserUtils.d.ts +13 -0
  27. package/dist/kameleoonUtils/browserUtils.js +72 -0
  28. package/dist/kameleoonUtils/browserUtils.js.map +1 -0
  29. package/dist/kameleoonUtils/nativeUtils.d.ts +12 -0
  30. package/dist/kameleoonUtils/nativeUtils.js +68 -0
  31. package/dist/kameleoonUtils/nativeUtils.js.map +1 -0
  32. package/dist/storage/index.d.ts +2 -0
  33. package/dist/storage/index.js +8 -0
  34. package/dist/storage/index.js.map +1 -0
  35. package/dist/storage/localStorage.d.ts +4 -0
  36. package/dist/storage/localStorage.js +44 -0
  37. package/dist/storage/localStorage.js.map +1 -0
  38. package/dist/storage/nativeStorage.d.ts +4 -0
  39. package/dist/storage/nativeStorage.js +41 -0
  40. package/dist/storage/nativeStorage.js.map +1 -0
  41. package/dist/useAddData.d.ts +14 -9
  42. package/dist/useAddData.js +14 -5
  43. package/dist/useAddData.js.map +1 -1
  44. package/dist/useBrowserVisitorCode.d.ts +17 -0
  45. package/dist/useBrowserVisitorCode.js +20 -0
  46. package/dist/useBrowserVisitorCode.js.map +1 -0
  47. package/dist/useConfigurationUpdate.d.ts +17 -0
  48. package/dist/useConfigurationUpdate.js +29 -0
  49. package/dist/useConfigurationUpdate.js.map +1 -0
  50. package/dist/useError.d.ts +1 -1
  51. package/dist/useError.js +1 -3
  52. package/dist/useError.js.map +1 -1
  53. package/dist/useErrors.d.ts +2 -2
  54. package/dist/useExperiments.d.ts +18 -0
  55. package/dist/useExperiments.js +30 -0
  56. package/dist/useExperiments.js.map +1 -0
  57. package/dist/useFeatureFlagActive.d.ts +19 -0
  58. package/dist/useFeatureFlagActive.js +30 -0
  59. package/dist/useFeatureFlagActive.js.map +1 -0
  60. package/dist/useFeatureFlagVariationKey.d.ts +19 -0
  61. package/dist/useFeatureFlagVariationKey.js +30 -0
  62. package/dist/useFeatureFlagVariationKey.js.map +1 -0
  63. package/dist/useFeatureFlags.d.ts +18 -0
  64. package/dist/useFeatureFlags.js +30 -0
  65. package/dist/useFeatureFlags.js.map +1 -0
  66. package/dist/useFeatureVariable.d.ts +12 -8
  67. package/dist/useFeatureVariable.js +7 -18
  68. package/dist/useFeatureVariable.js.map +1 -1
  69. package/dist/useFlushData.d.ts +14 -0
  70. package/dist/useFlushData.js +21 -0
  71. package/dist/useFlushData.js.map +1 -0
  72. package/dist/useInitialize.d.ts +15 -0
  73. package/dist/{useAsyncVisitorCode.js → useInitialize.js} +28 -10
  74. package/dist/useInitialize.js.map +1 -0
  75. package/dist/useKameleoon.d.ts +8 -7
  76. package/dist/useKameleoon.js +3 -1
  77. package/dist/useKameleoon.js.map +1 -1
  78. package/dist/useNativeVisitorCode.d.ts +16 -0
  79. package/dist/useNativeVisitorCode.js +20 -0
  80. package/dist/useNativeVisitorCode.js.map +1 -0
  81. package/dist/useRemoteData.d.ts +19 -0
  82. package/dist/{useRetrieveDataFromRemoteSource.js → useRemoteData.js} +25 -28
  83. package/dist/useRemoteData.js.map +1 -0
  84. package/dist/useTrackConversion.d.ts +18 -0
  85. package/dist/useTrackConversion.js +29 -0
  86. package/dist/useTrackConversion.js.map +1 -0
  87. package/dist/useTriggerExperiment.d.ts +12 -10
  88. package/dist/useTriggerExperiment.js +8 -9
  89. package/dist/useTriggerExperiment.js.map +1 -1
  90. package/dist/useVisitorExperiments.d.ts +20 -0
  91. package/dist/useVisitorExperiments.js +30 -0
  92. package/dist/useVisitorExperiments.js.map +1 -0
  93. package/dist/useVisitorFeatureFlags.d.ts +19 -0
  94. package/dist/useVisitorFeatureFlags.js +30 -0
  95. package/dist/useVisitorFeatureFlags.js.map +1 -0
  96. package/package.json +9 -4
  97. package/dist/Feature.d.ts +0 -11
  98. package/dist/Feature.js +0 -26
  99. package/dist/Feature.js.map +0 -1
  100. package/dist/compose.d.ts +0 -8
  101. package/dist/compose.js +0 -58
  102. package/dist/compose.js.map +0 -1
  103. package/dist/getKameleoonException.d.ts +0 -2
  104. package/dist/getKameleoonException.js +0 -34
  105. package/dist/getKameleoonException.js.map +0 -1
  106. package/dist/types.d.ts +0 -37
  107. package/dist/types.js +0 -4
  108. package/dist/types.js.map +0 -1
  109. package/dist/useActivateFeature.d.ts +0 -14
  110. package/dist/useActivateFeature.js +0 -32
  111. package/dist/useActivateFeature.js.map +0 -1
  112. package/dist/useAsyncVisitorCode.d.ts +0 -12
  113. package/dist/useAsyncVisitorCode.js.map +0 -1
  114. package/dist/useBrowser.d.ts +0 -13
  115. package/dist/useBrowser.js +0 -22
  116. package/dist/useBrowser.js.map +0 -1
  117. package/dist/useConversion.d.ts +0 -14
  118. package/dist/useConversion.js +0 -18
  119. package/dist/useConversion.js.map +0 -1
  120. package/dist/useCustomData.d.ts +0 -13
  121. package/dist/useCustomData.js +0 -18
  122. package/dist/useCustomData.js.map +0 -1
  123. package/dist/useDevice.d.ts +0 -12
  124. package/dist/useDevice.js +0 -16
  125. package/dist/useDevice.js.map +0 -1
  126. package/dist/useFeature.d.ts +0 -5
  127. package/dist/useFeature.js +0 -101
  128. package/dist/useFeature.js.map +0 -1
  129. package/dist/useFlush.d.ts +0 -11
  130. package/dist/useFlush.js +0 -19
  131. package/dist/useFlush.js.map +0 -1
  132. package/dist/usePageView.d.ts +0 -14
  133. package/dist/usePageView.js +0 -18
  134. package/dist/usePageView.js.map +0 -1
  135. package/dist/useRetrieveDataFromRemoteSource.d.ts +0 -12
  136. package/dist/useRetrieveDataFromRemoteSource.js.map +0 -1
  137. package/dist/useRunWhenReady.d.ts +0 -14
  138. package/dist/useRunWhenReady.js +0 -23
  139. package/dist/useRunWhenReady.js.map +0 -1
  140. package/dist/useTrackingConversion.d.ts +0 -13
  141. package/dist/useTrackingConversion.js +0 -19
  142. package/dist/useTrackingConversion.js.map +0 -1
  143. package/dist/useVariationAssociatedData.d.ts +0 -16
  144. package/dist/useVariationAssociatedData.js +0 -30
  145. package/dist/useVariationAssociatedData.js.map +0 -1
  146. package/dist/useVisitorCode.d.ts +0 -12
  147. package/dist/useVisitorCode.js +0 -19
  148. package/dist/useVisitorCode.js.map +0 -1
  149. package/dist/withActivateFeature.d.ts +0 -17
  150. package/dist/withActivateFeature.js +0 -28
  151. package/dist/withActivateFeature.js.map +0 -1
  152. package/dist/withAddData.d.ts +0 -16
  153. package/dist/withAddData.js +0 -28
  154. package/dist/withAddData.js.map +0 -1
  155. package/dist/withAsyncVisitorCode.d.ts +0 -15
  156. package/dist/withAsyncVisitorCode.js +0 -75
  157. package/dist/withAsyncVisitorCode.js.map +0 -1
  158. package/dist/withBrowser.d.ts +0 -16
  159. package/dist/withBrowser.js +0 -35
  160. package/dist/withBrowser.js.map +0 -1
  161. package/dist/withConversion.d.ts +0 -17
  162. package/dist/withConversion.js +0 -31
  163. package/dist/withConversion.js.map +0 -1
  164. package/dist/withCustomData.d.ts +0 -16
  165. package/dist/withCustomData.js +0 -31
  166. package/dist/withCustomData.js.map +0 -1
  167. package/dist/withDevice.d.ts +0 -15
  168. package/dist/withDevice.js +0 -29
  169. package/dist/withDevice.js.map +0 -1
  170. package/dist/withFeature.d.ts +0 -6
  171. package/dist/withFeature.js +0 -31
  172. package/dist/withFeature.js.map +0 -1
  173. package/dist/withFeatureVariable.d.ts +0 -17
  174. package/dist/withFeatureVariable.js +0 -28
  175. package/dist/withFeatureVariable.js.map +0 -1
  176. package/dist/withFlush.d.ts +0 -14
  177. package/dist/withFlush.js +0 -36
  178. package/dist/withFlush.js.map +0 -1
  179. package/dist/withKameleoon.d.ts +0 -13
  180. package/dist/withKameleoon.js +0 -33
  181. package/dist/withKameleoon.js.map +0 -1
  182. package/dist/withPageView.d.ts +0 -17
  183. package/dist/withPageView.js +0 -31
  184. package/dist/withPageView.js.map +0 -1
  185. package/dist/withRetrieveDataFromRemoteSource.d.ts +0 -14
  186. package/dist/withRetrieveDataFromRemoteSource.js +0 -28
  187. package/dist/withRetrieveDataFromRemoteSource.js.map +0 -1
  188. package/dist/withRunWhenReady.d.ts +0 -16
  189. package/dist/withRunWhenReady.js +0 -28
  190. package/dist/withRunWhenReady.js.map +0 -1
  191. package/dist/withTrackingConversion.d.ts +0 -16
  192. package/dist/withTrackingConversion.js +0 -36
  193. package/dist/withTrackingConversion.js.map +0 -1
  194. package/dist/withTriggerExperiment.d.ts +0 -19
  195. package/dist/withTriggerExperiment.js +0 -30
  196. package/dist/withTriggerExperiment.js.map +0 -1
  197. package/dist/withVariationAssociatedData.d.ts +0 -18
  198. package/dist/withVariationAssociatedData.js +0 -30
  199. package/dist/withVariationAssociatedData.js.map +0 -1
  200. package/dist/withVisitorCode.d.ts +0 -15
  201. package/dist/withVisitorCode.js +0 -36
  202. package/dist/withVisitorCode.js.map +0 -1
package/README.md CHANGED
@@ -1,1499 +1,105 @@
1
- # Kameleoon React SDK
1
+ # Kameleoon React/React Native SDK
2
2
 
3
- ### Introduction
4
- This repository is a Kameleoon React SDK which is used to run experiments and get feature flag status and its variables. Integration of this SDK into web application is easy, and its footprint is low.
3
+ ## Introduction
5
4
 
6
- ### Requirements
7
- This React SDK requires `React 16.8.0+`
5
+ Kameleoon React/React Native SDK is used to work with Kameleoon Feature Flags and Experiments.
6
+ Integration of this SDK on web/mobile is easy, and its footprint is low.
8
7
 
9
- ### Installation
10
- Installing the React SDK can be directly achieved through an `npm` or `yarn` module:
8
+ This page describes the most basic configuration, for more in-depth review of all the hooks and configuration options follow [Official Kameleoon Documentation](https://developers.kameleoon.com/react-js-sdk.html)
11
9
 
12
- **npm**
13
- ```
14
- npm install @kameleoon/react-sdk
15
- ```
16
-
17
- **yarn**
18
- ```
19
- yarn add @kameleoon/react-sdk
20
- ```
21
-
22
- ### Usage
23
-
24
- ## `createClient`
25
- A `KameleoonClient` created using `createClient()` to run experiments and retrive the status of feature flag and its variables.
26
-
27
- #### Arguments
28
- - `clientParams: ICreateClientParams`
29
- - `siteCode: string` - code of the website on which experiments run. This unique code id can be found in our platform.
30
- - `visitorCode: string` (optional) - visitor code is an optional parameter, if it is used, it automatically create custom data to check if visitor is targeted.
31
- - `option: SDKConfiguration` (optional) - JSON object filled with configuration parameters.
32
- - `actions_configuration_refresh_interval: number` (optional) - an option specifying the refresh interval, in minutes, of the configuration for experiments and feature flags (the active experiments and feature flags are fetched from the Kameleoon servers). It means that once you launch an experiment, pause it, or stop it the changes can take (at most) the duration of this interval to be propagated in production to your servers. If not specified, the **default interval is 60 minutes**.
33
- - `visitor_data_maximum_size: number` (optional) - an option specifying the maximum amount of memory that [the map holding all the visitor data](https://developers.kameleoon.com/javascript-sdk.html#technical-considerations) (in particular custom data) can take (in MB on the browser LocalStorage). If specified, **max size is 5MB**. If not specified, the **default size is 1MB**.
34
- - `environment: string` (optional) - an option specifying which feature flag configuration will be used, by default each feature flag is split into **production**, **staging**, **development**. If not specified, will be set to **default value** of **production**.
35
-
36
- **NOTICE:** make sure not to use several client instances in one application with different `environment` as it is not fully supported yet and might lead to local storage configuration being overwritten and cause bugs.
37
-
38
- #### Returns
39
- - A `KameleoonClient` instance.
40
-
41
- #### Example
42
- ```jsx
43
- import { createClient } from '@kameleoon/react-sdk';
44
-
45
- const client = createClient({
46
- siteCode: 'dfl102d38e',
47
- visitorCode: '280295',
48
- options: {
49
- visitor_data_maximum_size: 1,
50
- actions_configuration_refresh_interval: 60,
51
- environment: 'staging'
52
- }
53
- });
54
- ```
55
-
56
- ## `<KameleoonProvider>`
57
- Use this provider in root level by wrapping your app to gain an access to `KameleoonClient`. This ensures your app does not flicker due to flag changes at startup time.
58
-
59
- #### Props
60
- - `children: ReactNode` - child elements of the provider.
61
- - `client: KameleoonClient` - `KameleoonClient` instance created by `createClient()`.
62
-
63
- #### Example
64
- ```jsx
65
- import { KameleoonProvider, createClient } from '@kameleoon/react-sdk';
66
-
67
- const client = createClient({
68
- siteCode: 'dfl102d38e'
69
- visitorCode: '280295',
70
- options: {
71
- visitor_data_maximum_size: 1,
72
- actions_configuration_refresh_interval: 60,
73
- environment: 'staging'
74
- }
75
- });
76
-
77
- function AppWrapper(): JSX.Element {
78
- return (
79
- <KameleoonProvider client={client}>
80
- <App />
81
- </KameleoonProvider>
82
- )
83
- }
84
- ```
85
-
86
- ## Kameleoon client
87
- These Hook and HOC validate whether they are used within `KameleoonProvider` and provide an access to `KameleoonClient`.
88
-
89
- ### `useKameleoon`
90
- #### Returns
91
- - Returns `object: KameleoonHookResult`:
92
- - `client: KameleoonClient` - an instance of `KameleoonClient` taken from context.
93
-
94
- #### Example
95
- ```jsx
96
- import { useKameleoon } from '@kameleoon/react-sdk';
97
-
98
- function MyComponent(): JSX.Element {
99
- const { client } = useKameleoon();
100
-
101
- ...
102
- }
103
- ```
104
-
105
- ### `withKameleoon`
106
- #### Returns
107
- - `Component: React.Component` - component which will be enhanced with the prop `client: KameleoonClient`.
108
-
109
- ```jsx
110
- import { withKameleoon } from '@kameleoon/react-sdk';
111
-
112
- class MyComponent extends React.Component {
113
- componentDidMount() {
114
- const { client } = this.props;
115
- }
116
-
117
- ...
118
- }
119
-
120
- export default withKameleoon(MyComponent);
121
- ```
122
-
123
- ## LocalStorage Key
124
- - `KAMELEOON_SDK_LOCAL_STORAGE_KEY` - is a constant which used as a key in `LocalStorage` to store a `kameleoonTargetingData` and `kameleoonConfiguration`.
125
-
126
- ```jsx
127
- import { KAMELEOON_SDK_LOCAL_STORAGE_KEY } from '@kameleoon/react-sdk'
128
- ```
129
-
130
- ## Obtain status and variables of feature flag
131
- Returns the status of a feature flag and its variables.
132
-
133
- #### Arguments
134
- - `featureParams: IFeatureParams`
135
- - `featureKey: string | number` - unique identifier or key of the feature you want to expose to a user.
136
- - `variableKeys: VariableKeysType` - keys for the variables on different environments.
137
- - `visitorCode: string` (optional) - unique identifier of the user.
138
-
139
- #### Returns
140
- - `errors: KameleoonException[]` - an array of errors thrown as a result of getting variables or feature flag status.
141
- - `feature` - an object containing feature flag status and variables
142
- - `isActive: boolean` - feature flag status.
143
- - `variables: FeatureVariableType[]` - feature flag variables.
144
-
145
- #### Exceptions
146
- - `KameleoonException.NotTargeted` - Exception indicating that the current visitor / user did not trigger the required targeting conditions for this feature. The targeting conditions are defined via Kameleoon's segment builder.
147
- - `KameleoonException.FeatureConfigurationNotFound` - Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side).
148
-
149
-
150
- In this examples, if the feature flag with the `red-button` key is enabled, theme of button will set to red.
151
- ### `useFeature`
152
- #### Example
153
- ```jsx
154
- import { Button } from '@kameleoon/ui';
155
- import { useFeature, useVisitorCode, KameleoonException } from '@kameleoon/react-sdk';
156
-
157
- function MyComponent(): JSX.Element {
158
- const { getVisitorCode } = useVisitorCode();
159
- const { feature, errors } = useFeature({
160
- featureKey: 'red-button',
161
- variableKeys: { production: 'red-button' },
162
- visitorCode: getVisitorCode('example.com'),
163
- });
164
-
165
- for (const error of errors) {
166
- if (error.type === KameleoonException.NotTargeted) {
167
- // Handle error
168
- }
169
-
170
- if (error.type === KameleoonException.FeatureConfigurationNotFound) {
171
- // Handle error
172
- }
173
- }
174
-
175
- const { isActive, variables } = feature;
176
-
177
- return <Button theme={isActive ? 'red' : 'green'} />;
178
- }
179
- ```
180
-
181
- ### `withFeature`
182
- #### Example
183
- ```jsx
184
- import { Button } from '@kameleoon/ui';
185
- import { withFeature, KameleoonException } from '@kameleoon/react-sdk';
186
-
187
- class MyComponent extends React.Component {
188
- state = {
189
- isActive: false,
190
- variables: [],
191
- }
192
-
193
- componentDidMount() {
194
- const { feature, errors } = this.props;
195
-
196
- for (const error of errors) {
197
- if (error.type === KameleoonException.NotTargeted) {
198
- // Handle error
199
- }
200
-
201
- if (error.type === KameleoonException.FeatureConfigurationNotFound) {
202
- // Handle error
203
- }
204
- }
205
-
206
- const { isActive, variables } = feature;
207
-
208
- this.setState({ isActive, variables });
209
- }
210
-
211
- render() {
212
- return <Button theme={this.isActive ? 'red' : 'green'} />;
213
- }
214
- }
215
-
216
- export default withFeature({
217
- featureKey: 'red-button',
218
- variableKeys: { production: 'red-button' },
219
- visitorCode: '280295'
220
- })(MyComponent);
221
- ```
222
-
223
- ### `Feature` render props
224
- #### Props
225
- - `children: (featureResult: IFeature) => ReactNode` - child elements of `Feature`.
226
- - `featureKey: string | number` - unique identifier or key of the feature you want to expose to a user.
227
- - `variableKeys: VariableKeysType` - keys for the variables on different environments.
228
- - `visitorCode: string` - unique identifier of the user.
229
-
230
- #### Returns
231
- A wrapped component with the following props:
232
- - `errors: KameleoonException[]` - an array of errors thrown as a result of getting variables or feature flag status.
233
- - `feature` - an object containing feature flag status and variables
234
- - `isActive: boolean` - feature flag status.
235
- - `variables: FeatureVariableType[]` - feature flag variables.
236
-
237
- #### Example
238
- ```jsx
239
- import { Button } from '@kameleoon/ui';
240
- import { Feature } from '@kameleoon/react-sdk';
241
-
242
- class MyComponent extends React.Component {
243
- state = {
244
- isActive: false,
245
- variables: [],
246
- }
247
-
248
- componentDidMount() {
249
- const { feature, errors } = this.props;
250
-
251
- for (const error of errors) {
252
- if (error.type === KameleoonException.NotTargeted) {
253
- // Handle error
254
- }
255
-
256
- if (error.type === KameleoonException.FeatureConfigurationNotFound) {
257
- // Handle error
258
- }
259
- }
260
-
261
- const { isActive, variables } = feature;
262
-
263
- this.setState({ isActive, variables });
264
- }
265
-
266
- render() {
267
- return <Button theme={this.isActive ? 'red' : 'green'} />;
268
- }
269
- }
270
-
271
- class MyComponentWrapper extends React.Component {
272
- render() {
273
- return(
274
- <Feature
275
- featureKey="red-button"
276
- variableKeys={{production: "red-button"}}
277
- visitorCode="280295"
278
- >
279
- (({ feature, errors }) => (
280
- <MyComponent feature={feature} errors={errors} />
281
- ))
282
- </Feature>;
283
- )
284
- }
285
- }
286
- ```
287
-
288
- ## Obtain visitorCode
289
- A callback function `getVisitorCode()` retrieves the Kameleoon `visitorCode` for the current visitor. This is especially important when using Kameleoon in a mixed front-end and back-end environment, where user identification consistency must be guaranteed. The implementation logic is described here:
290
-
291
- 1. First we check if a `kameleoonVisitorCode` cookie can be found. If so, we will use this as the visitor identifier.
292
-
293
- 2. If no cookie is found, we either randomly generate a new identifier, or use the `defaultVisitorCode` argument as identifier if it is passed. This allows our customers to use their own identifiers as visitor codes, should they wish to. This can have the added benefit of matching Kameleoon visitors with their own users without any additional look-ups in a matching table.
294
-
295
- 3. In any case, the JavaScript `kameleoonVisitorCode` cookie is set with the value. Then this identifier value is finally returned by the method.
296
-
297
- For more information, refer to [this article](https://developers.kameleoon.com/back-front-bridge.html).
298
-
299
- There is also an alternative `getAsyncVisitorCode()` callback, which is asynchronous and is meant for *ReactNative* applications.
300
-
301
- ##### Please Note:
302
- _If you provide your own `visitorCode`, its uniqueness must be guaranteed on your end - the SDK cannot check it. Also note that the length of `visitorCode` is **limited to 255 characters**. Any excess characters will throw an exception._
303
-
304
- #### `getVisitorCode()`
305
-
306
- ##### Arguments
307
- - `topLevelDomain: string` - current top level domain for the concerned site (this information is needed to set the corresponding cookie accordingly, on the top level domain).
308
- - `defaultVisitorCode: string` (optional) - This parameter will be used as the `visitorCode` if no existing `kameleoonVisitorCode` cookie is found on the request. This field is optional, and by default a random `visitorCode` will be generated.
309
-
310
- ##### Returns
311
- - `visitorCode: string` - a visitorCode that will be associated with this particular user and should be used with most of the methods of the SDK.
312
-
313
- ### `useVisitorCode`
314
- #### Returns
315
- - A callback function `getVisitorCode()`.
316
-
317
- #### Example
318
- ```jsx
319
- import { useEffect } from 'react';
320
- import { uuidv4 } from 'uuid';
321
- import { useVisitorCode } from '@kameleoon/react-sdk';
322
-
323
- function MyComponent(): JSX.Element {
324
- const { getVisitorCode } = useVisitorCode();
325
-
326
- useEffect(() => {
327
- // Without defaultVisitorCode argument
328
- const visitorCode = getVisitorCode('example.com');
329
-
330
- // With defaultVisitorCode argument
331
- const visitorCode = getVisitorCode('example.com', uuidv4());
332
- }, []);
333
-
334
- ...
335
- }
336
- ```
337
- ### `withVisitorCode`
338
- #### Arguments
339
- - `Component: React.Component` - component which will be enhanced with the prop `getVisitorCode()`.
340
-
341
- #### Returns
342
- - A wrapped component with additional props as described above.
343
-
344
- #### Example
345
- ```jsx
346
- import { uuidv4 } from 'uuid';
347
- import { withVisitorCode } from '@kameleoon/react-sdk';
348
-
349
- class MyComponent extends React.Component {
350
- componentDidMount() {
351
- const { getVisitorCode } = this.props;
352
-
353
- // Without defaultVisitorCode argument
354
- const visitorCode = getVisitorCode('example.com');
355
-
356
- // With defaultVisitorCode argument
357
- const visitorCode = getVisitorCode('example.com', uuidv4());
358
- }
359
-
360
- ...
361
- }
362
-
363
- export default withVisitorCode(MyComponent);
364
- ```
365
-
366
- ### `useAsyncVisitorCode`
367
- #### Returns
368
- - A callback function `getAsyncVisitorCode()`.
369
-
370
- #### Example
371
- ```jsx
372
- import { useState } from 'react';
373
- import { uuidv4 } from 'uuid';
374
- import { useAsyncVisitorCode } from '@kameleoon/react-sdk';
375
-
376
- function MyComponent(): JSX.Element {
377
- const { getAsyncVisitorCode } = useAsyncVisitorCode();
378
- const [visitorCode, setVisitorCode] = useState<string>('');
379
-
380
- async function retrieveVisitorCode(): Promise<void> {
381
- // Without defaultVisitorCode argument
382
- const result = await getAsyncVisitorCode('example.com');
383
- // With defaultVisitorCode argument
384
- const result = await getAsyncVisitorCode('example.com', uuidv4());
385
-
386
- setVisitorCode(result);
387
- }
388
- ...
389
- }
390
- ```
391
- ### `withAsyncVisitorCode`
392
- #### Arguments
393
- - `Component: React.Component` - component which will be enhanced with the prop `getAsyncVisitorCode()`.
394
-
395
- #### Returns
396
- - A wrapped component with additional props as described above.
397
-
398
- #### Example
399
- ```jsx
400
- import { uuidv4 } from 'uuid';
401
- import { withAsyncVisitorCode } from '@kameleoon/react-sdk';
402
-
403
- class MyComponent extends React.Component {
404
- async componentDidMount(): Promise<void> {
405
- const { getAsyncVisitorCode } = this.props;
406
-
407
- // Without defaultVisitorCode argument
408
- const visitorCode = await getAsyncVisitorCode('example.com');
409
-
410
- // With defaultVisitorCode argument
411
- const visitorCode = await getAsyncVisitorCode('example.com', uuidv4());
412
- }
413
-
414
- ...
415
- }
416
-
417
- export default withVisitorCode(MyComponent);
418
- ```
419
-
420
- ## Triggering an experiment
421
- A callback function `getVariationId()` takes `visitorCode` and `experimentId` as mandatory arguments to register a variation for a given user.
422
-
423
- If such a user has never been associated with any variation, the SDK returns a randomly selected variation. If a user with a given `visitorCode` is already registered with a variation, it will detect the previously registered variation and return the `variationId`.
424
-
425
- You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.
426
-
427
- ##### Please Note:
428
- _By convention, the reference (original variation) always has an ID equal to **0**._
429
-
430
- #### Exceptions
431
- - `KameleoonException.NotTargeted` - Exception indicating that the current visitor / user did not trigger the required targeting conditions for this experiment. The targeting conditions are defined via Kameleoon's segment builder.
432
- - `KameleoonException.NotActivated` - Exception indicating that the current visitor / user triggered the experiment (met the targeting conditions), but did not activate it. The most common reason for that is that part of the traffic has been excluded from the experiment and should not be tracked.
433
- - `KameleoonException.ExperimentConfigurationNotFound` - Exception indicating that the requested experiment ID has not been found in the internal configuration of the SDK. This is usually normal and means that the experiment has not yet been started on Kameleoon's side (but code triggering / implementing variations is already deployed on the web-application's side).
434
-
435
- #### `getVariationId()`
436
- ##### Arguments
437
- - `visitorCode: string` - unique identifier of the user
438
- - `experimentId: number` - unique identifier of the experiment you want to expose to a user
439
-
440
- ##### Returns
441
- - `variationId: number` - ID of the variation that is registered for a given visitorCode. By convention, the reference (original variation) always has an ID equal to **0**.
442
-
443
- ### `useTriggerExperiment`
444
- #### Returns
445
- - A callback function `getVariationId()`.
446
- - An `error` object containing `name`, `type` and `message` strings, certain type of exception can be handled using `error.type` and `KameleoonException`. If there is no errors on the client `error` will be `null`.
447
-
448
- #### Example
449
- ```jsx
450
- import { useEffect } from 'react';
451
- import { useTriggerExperiment, useVisitorCode, KameleoonException } from '@kameleoon/react-sdk';
452
-
453
- function MyComponent(): JSX.Element {
454
- const { getVariationId, error } = useTriggerExperiment();
455
- const { getVisitorCode } = useVisitorCode();
456
-
457
- useEffect(() => {
458
- const visitorCode = getVisitorCode('example.com');
459
- const experimentId = 12341;
460
-
461
- if (error?.type === KameleoonException.ExperimentConfigurationNotFound) {
462
- // Handle exception
463
- }
464
-
465
- if (error?.type === KameleoonException.NotTargeted) {
466
- // Handle exception
467
- }
468
-
469
- if (error?.type === KameleoonException.NotActivated) {
470
- // Handle exception
471
- }
472
-
473
- const variationId = getVariationId(visitorCode, experimentId);
474
- }, []);
475
-
476
- ...
477
- }
478
- ```
479
-
480
- ### `withTriggerExperiment`
481
- #### Arguments
482
- - `Component: React.Component` - component which will be enhanced with the prop `getVariationId()`.
483
-
484
- #### Returns
485
- - A wrapped component with additional props as described above.
486
-
487
- #### Example
488
- ```jsx
489
- import { withVisitorCode, withTriggerExperiment, compose, KameleoonException } from '@kameleoon/react-sdk';
490
-
491
- class MyComponent extends React.Component {
492
- componentDidMount() {
493
- const { getVisitorCode, getVariationId, triggerExperimentError } = this.props;
494
- const visitorCode = getVisitorCode('example.com');
495
- const experimentId = 230243;
496
-
497
- if (triggerExperimentError?.type === KameleoonException.ExperimentConfigurationNotFound) {
498
- // Handle exception
499
- }
500
-
501
- if (triggerExperimentError?.type === KameleoonException.NotTargeted) {
502
- // Handle exception
503
- }
504
-
505
- if (triggerExperimentError?.type === KameleoonException.NotActivated) {
506
- // Handle exception
507
- }
508
-
509
- const variationId = getVariationId(visitorCode, experimentId);
510
- }
511
-
512
- ...
513
- }
514
-
515
- export default compose(withVisitorCode, withTriggerExperiment)(MyComponent);
516
- ```
517
-
518
- ## Activate feature
519
- A callback function `hasFeature()` which validates if user has been associated with this feature. If it is fails, callback returns value **false**, otherwise **true**.
520
-
521
- If feature flag is not activated, `KameleoonException.FeatureConfigurationNotFound` exception will be thrown. Please, make sure to handle the error properly.
522
-
523
- #### Exceptions
524
- - `KameleoonException.NotTargeted` - Exception indicating that the current visitor / user did not trigger the required targeting conditions for this feature. The targeting conditions are defined via Kameleoon's segment builder.
525
- - `KameleoonException.FeatureConfigurationNotFound` - Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side).
526
-
527
- #### `hasFeature()`
528
- ##### Arguments
529
- - `featureKey: string | number` - unique identifier or key of the feature you want to expose to a user.
530
- - `visitorCode: string` (optional) - unique identifier of the user.
531
-
532
- ##### Returns
533
- - A `value: boolean` of the feature that is registered for a given `visitorCode`.
534
-
535
- ### `useActivateFeature`
536
- #### Returns
537
- - A callback function `hasFeature()`.
538
- - An `error` object containing `name`, `type` and `message` strings, certain type of exception can be handled using `error.type` and `KameleoonException`. If there is no errors on the client `error` will be `null`.
539
-
540
- #### Example
541
- ```jsx
542
- import { useEffect } from 'react';
543
- import { useActivateFeature, useVisitorCode, KameleoonException } from '@kameleoon/react-sdk';
544
-
545
- function MyComponent(): JSX.Element {
546
- const { hasFeature, error } = useActivateFeature();
547
- const { getVisitorCode } = useVisitorCode();
548
-
549
- useEffect(() => {
550
- const visitorCode = getVisitorCode('example.com');
551
- const featureKey = 'example-feature-key';
552
-
553
- if (error?.type === KameleoonException.FeatureConfigurationNotFound) {
554
- // Handle exception
555
- }
556
-
557
- if (error?.type === KameleoonException.NotTargeted) {
558
- // Handle exception
559
- }
560
-
561
- const feature = hasFeature(featureKey, visitorCode);
562
- }, []);
563
-
564
- ...
565
- }
566
- ```
567
-
568
- ### `withActivateFeature`
569
- #### Arguments
570
- - `Component: React.Component` - component which will be enhanced with the prop `hasFeature()` and `activateFeatureError`.
571
-
572
- #### Returns
573
- - A wrapped component with additional props as described above.
574
-
575
- #### Example
576
- ```jsx
577
- import { withVisitorCode, withActivateFeature, KameleoonException, compose } from '@kameleoon/react-sdk';
578
-
579
- class MyComponent extends React.Component {
580
- componentDidMount() {
581
- const { getVisitorCode, hasFeature, activateFeatureError } = this.props;
582
- const visitorCode = getVisitorCode('example.com');
583
- const featureKey = 'example-feature-key';
584
-
585
- if (activateFeatureError?.type === KameleoonException.FeatureConfigurationNotFound) {
586
- // Handle exception
587
- }
588
-
589
- if (activateFeatureError?.type === KameleoonException.NotTargeted) {
590
- // Handle exception
591
- }
592
-
593
- const feature = hasFeature(featureKey, visitorCode);
594
- }
595
-
596
- ...
597
- }
598
-
599
- export default compose(withVisitorCode, withActivateFeature)(MyComponent);
600
- ```
601
-
602
- ## Obtain variation associated data
603
- A callback function `getVariationAssociatedData()` which retrieves JSON data associated with a variation. The JSON data usually represents some metadata of the variation, and can be configured on our web application interface or via our Automation API.
604
-
605
- This callback function takes the `variationId` as a parameter and will return the data as a JavaScript object. It will throw an exception `(KameleoonException.VariationConfigurationNotFound)` if the `variationId` is wrong or corresponds to an experiment that is not yet online.
606
-
607
- #### Exceptions
608
- - `KameleoonException.VariationConfigurationNotFound` - Exception indicating that the requested variation ID has not been found in the internal configuration of the SDK. This is usually normal and means that the variation's corresponding experiment has not yet been activated on Kameleoon's side.
609
-
610
- #### `getVariationAssociatedData()`
611
-
612
- ##### Arguments
613
- - `variationId: number` - unique identifier of the variation you want to obtain associated data for.
614
-
615
- ##### Returns
616
- - Data associated with this `variationId`.
617
-
618
- ### `useVariationAssociatedData`
619
- #### Returns
620
- - A callback function `getVariationAssociatedData()`.
621
- - An `error` object containing `name`, `type` and `message` strings, certain type of exception can be handled using `error.type` and `KameleoonException`. If there is no errors on the client `error` will be `null`.
622
-
623
- #### Example
624
- ```jsx
625
- import { useEffect } from 'react';
626
- import { useVariationAssociatedData, KameleoonException } from '@kameleoon/react-sdk';
627
-
628
- function MyComponent(): JSX.Element {
629
- const { getVariationAssociatedData, error } = useVariationAssociatedData();
630
-
631
- useEffect(() => {
632
- const variationId = 280295;
633
-
634
- if (error?.type === KameleoonException.VariationConfigurationNotFound) {
635
- // Handle error
636
- }
637
-
638
- const data = getVariationAssociatedData(variationId);
639
- }, []);
640
-
641
- ...
642
- }
643
- ```
644
- ### `withVariationAssociatedData`
645
- #### Arguments
646
- - `Component: React.Component` - component which will be enhanced with the prop `getVariationAssociatedData()`.
647
-
648
- #### Returns
649
- - A wrapped component with additional props as described above.
650
-
651
- #### Example
652
- ```jsx
653
- import { withVariationAssociatedData, KameleoonException } from '@kameleoon/react-sdk';
654
-
655
- class MyComponent extends React.Component {
656
- componentDidMount() {
657
- const { getVariationAssociatedData, variationAssociatedDataError } = this.props;
658
- const variationId = 280295;
659
-
660
- if (variationAssociatedDataError?.type === KameleoonException.VariationConfigurationNotFound) {
661
- // Handle error
662
- }
663
-
664
- const data = getVariationAssociatedData(variationId);
665
- }
666
-
667
- ...
668
- }
669
-
670
- export default withVariationAssociatedData(MyComponent);
671
- ```
672
-
673
- ## Obtain data from remote source
674
- An callback function `retrieveDataFromRemoteSource()` can be used to retrieve data using specific key and siteCode from Kameleoon provider. The Data is stored on a remote Kameleoon server. Usually data will be stored on our remote servers via the use of our Data API. This method, along with the availability of our highly scalable servers for this purpose, provides a convenient way to quickly store massive amounts of data that can be later retrieved for each of your visitors / users.
675
-
676
- Note that since a server call is required, this mechanism is asynchronous, make sure to properly handle promise which will be returned from a function call.
677
-
678
-
679
- #### Exceptions Thrown
680
- - Local Error will be thrown if remote source data couldn't be accessed or retrieved data contains an empty JSON.
681
-
682
- #### `retrieveDataFromRemoteSource()`
683
-
684
- ##### Arguments
685
- - `key: string` - unique key for the current siteCode used to store data on the remote source (can be created via `POST` request to Kameleoon Data API). This field is mandatory.
686
-
687
- ##### Returns
688
- - JSON object with the data posted to Kameleoon Data API.
689
-
690
- #### Types
691
- - `RemoteSourceDataType` can be used for handling data type.
692
-
693
- ### `useRetrieveDataFromRemoteSource`
694
- #### Returns
695
- - A callback function `retrieveDataFromRemoteSource()`.
696
-
697
- #### Example
698
- ```jsx
699
- import { useEffect, useCallback } from 'react';
700
- import { useRetrieveDataFromRemoteSource, RemoteSourceDataType } from '@kameleoon/react-sdk';
701
-
702
- function MyComponent(): JSX.Element {
703
- const { retrieveDataFromRemoteSource } = useRetrieveDataFromRemoteSource();
704
-
705
- const processRetrievedData = useCallback(async () => {
706
- const data: RemoteSourceDataType = await retrieveDataFromRemoteSource('example-key');
707
- // Your code
708
- }, [retrieveDataFromRemoteSource]);
709
-
710
- useEffect(() => {
711
- processRetrievedData();
712
- }, [processRetrievedData]);
713
-
714
- ...
715
- }
716
- ```
717
- ### `withRetrieveDataFromRemoteSource`
718
- #### Arguments
719
- - `Component: React.Component` - component which will be enhanced with the prop `retrieveDataFromRemoteSource()`.
720
-
721
- #### Returns
722
- - A wrapped component with additional props as described above.
723
-
724
- #### Example
725
- ```jsx
726
- import { withRetrieveDataFromRemoteSource, RemoteSourceDataType } from '@kameleoon/react-sdk';
727
-
728
- class MyComponent extends React.Component {
729
- async componentDidMount() {
730
- const { retrieveDataFromRemoteSource } = this.props;
731
- const data: RemoteSourceDataType = await getVariationAssociatedData('example-key');
732
- // Your code
733
- }
734
-
735
- ...
736
- }
737
-
738
- export default withRetrieveDataFromRemoteSource(MyComponent);
739
- ```
740
-
741
- ## Obtain feature variable
742
- A callback function `getFeatureVariable()` which retrieves a feature variable.
743
-
744
- This callback function takes two input parameters: `featureKey` and `variableKey`. It will return the data with the expected type, as defined on the web interface. It will throw an exception `(KameleoonException.FeatureConfigurationNotFound)` if the requested feature has not been found in the internal configuration of the SDK.
745
-
746
- #### Exceptions Thrown
747
- - `KameleoonException.FeatureConfigurationNotFound` - Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side.
748
-
749
- #### `getFeatureVariable()`
750
-
751
- ##### Arguments
752
- - `featureKey: string | number` - unique identifier or key of the feature you want to obtain to a user.
753
- - `variableKey: string` - key of the variable.
754
- ##### Returns
755
- - `featureVariable: FeatureFlagVariableType` - data associated with this variable for this feature flag
756
-
757
- ### `useFeatureVariable`
758
- #### Returns
759
- - A callback function `getFeatureVariable()`.
760
-
761
- #### Example
762
- ```jsx
763
- import { useEffect } from 'react';
764
- import { useFeatureVariable } from '@kameleoon/react-sdk';
10
+ ## Contents
765
11
 
766
- function MyComponent(): JSX.Element {
767
- const { getFeatureVariable } = useFeatureVariable();
768
-
769
- useEffect(() => {
770
- const featureKey = 'example-feature-key';
771
- const variableKey = 'example-variable-key';
772
-
773
- const featureVariable = getFeatureVariable(featureKey, variableKey);
774
- }, []);
775
-
776
- ...
777
- }
778
- ```
779
-
780
- ### `withFeatureVariable`
781
- #### Arguments
782
- - `Component: React.Component` - component which will be enhanced with the prop `getFeatureVariable()`.
783
-
784
- #### Returns
785
- - A wrapped component with additional props as described above.
786
-
787
- #### Example
788
- ```jsx
789
- import { withFeatureVariable } from '@kameleoon/react-sdk';
790
-
791
- class MyComponent extends React.Component {
792
- componentDidMount() {
793
- const { getFeatureVariable } = this.props;
794
- const featureKey = 'example-feature-key';
795
- const variableKey = 'example-variable-key';
796
-
797
- const featureVariable = getFeatureVariable(featureKey, variableKey);
798
- }
799
-
800
- ...
801
- }
802
-
803
- export default withFeatureVariable(MyComponent);
804
- ```
805
-
806
- ## Tracking conversion
807
- A callback function `trackConversion()` which tracks conversion. This callback function requires `visitorCode` and `goalId` to track conversion on this particular goal. In addition, `trackConverion()` accepts third optional argument `revenue` to track revenue. The `visitorCode` is usually identical to the one that was used when triggering the experiment.
808
-
809
- This callback function doesn't return any value. And it is non-blocking as the server call is made asynchronously.
810
-
811
- #### `trackConversion()`
812
- ##### Arguments
813
- - `visitorCode: string` - unique identifier of the user.
814
- - `goalId: number` - key of the variable.
815
- - `revenue: number` (optional) - key of the variable.
816
-
817
- ### `useTrackingConversion`
818
- #### Returns
819
- - A callback function `trackConversion()`;
820
-
821
- #### Example
822
- ```jsx
823
- import { useEffect } from 'react';
824
- import { useTrackingConversion, useVisitorCode } from '@kameleoon/react-sdk';
825
-
826
- function MyComponent(): JSX.Element {
827
- const { getVisitorCode } = useVisitorCode();
828
- const { trackConversion } = useTrackingConversion();
829
-
830
- useEffect(() => {
831
- const visitorCode = getVisitorCode('example.com')
832
- const goalId = 280295;
833
-
834
- trackConversion(visitorCode, goalId);
835
- }, []);
836
-
837
- ...
838
- }
839
- ```
840
-
841
- ### `withTrackingConversion`
842
- #### Arguments
843
- - `Component: React.Component` - component which will be enhanced with the prop `trackConversion()`.
844
-
845
- #### Returns
846
- - A wrapped component with additional props as described above.
847
-
848
- #### Example
849
- ```jsx
850
- import { withVisitorCode, withTrackingConversion, compose } from '@kameleoon/react-sdk';
851
-
852
- class MyComponent extends React.Component {
853
- componentDidMount() {
854
- const { getVisitorCode, trackConversion } = this.props;
855
- const visitorCode = getVisitorCode('example.com');
856
- const goalId = 230234;
857
-
858
- trackConversion(visitorCode, goalId);
859
- }
860
-
861
- ...
862
- }
863
-
864
- export default compose(withVisitorCode, withTrackingConversion)(MyComponent);
865
- ```
866
-
867
-
868
- ## Add data
869
- A callback function `addData()` which adds various data to associate this data with the current user. This callback function requires `visitorCode` as a first parameter and then accepts array of various **Data Types** allowed in Kameleoon.
870
-
871
- Note that the `addData()` doesn't return any value and doesn't interact with the Kameleoon back-end servers by itself. Instead, all declared data is saved for further sending via the `flush()` described in the next paragraph. This reduces the number of server calls made, as data is usually grouped into a single server call triggered by the execution of `flush()`.
872
-
873
- ##### Please Note:
874
- _The `triggerExperiment()` and `trackConversion()` callback functions also sends out previously associated data, exactly as the `flush()`._
875
-
876
- #### `addData()`
877
- ##### Arguments
878
- - `visitorCode: string` - unique identifier of the user.
879
- - `dataTypes: DataInterface[]` - custom data types which may be passed separated by a comma.
880
-
881
- ### `useAddData`
882
- #### Returns
883
- - A callback function `addData()`.
884
-
885
- #### Example
886
- ```jsx
887
- import { useEffect } from 'react';
888
- import { Button } from '@kameleoon/ui';
889
- import {
890
- useAddData,
891
- useBrowser,
892
- useCutomData,
893
- useVisitorCode,
894
- Browser
895
- } from '@kameleoon/react-sdk';
896
-
897
- function MyComponent(): JSX.Element {
898
- const { getVisitorCode } = useVisitorCode();
899
- const { addData } = useAddData();
900
- const { addBrowser } = useBrowser();
901
- const { addCustomData } = useCutomData();
902
-
903
- useEffect(() => {
904
- const visitorCode = getVisitorCode('example.com');
905
-
906
- // Single data type passed
907
- addData(visitorCode, addBrowser(Browser.Chrome));
908
-
909
- // Several data types passed
910
- addData(visitorCode, addBrowser(Browser.Chrome), addCustomData(1, 'some custom value'));
911
- }, []);
912
-
913
- ...
914
- }
915
- ```
916
-
917
- ### `withAddData`
918
- #### Arguments
919
- - `Component: React.Component` - component which will be enhanced with the prop `addData()`.
920
-
921
- #### Returns
922
- - A wrapped component with additional props as described above.
923
-
924
- #### Example
925
- ```jsx
926
- import {
927
- withAddData,
928
- withBrowser,
929
- withCustomData,
930
- withVisitorCode,
931
- Browser,
932
- compose,
933
- } from '@kameleoon/react-sdk';
934
-
935
- class MyComponent extends React.Component {
936
- componentDidMount() {
937
- const { addData, addBrowser, addCustomData, getVisitorCode } = this.props;
938
- const visitorCode = getVisitorCode('example.com');
939
-
940
- // Single data type passed
941
- addData(visitorCode, addBrowser(Browser.Chrome));
942
-
943
- // Several data types passed
944
- addData(visitorCode, addBrowser(Browser.Chrome), addCustomData(1, 'some custom value'));
945
- }
946
-
947
- ...
948
- }
949
-
950
- export default compose(
951
- withAddData,
952
- withBrowser,
953
- withCustomData,
954
- withVisitorCode,
955
- )(MyComponent);
956
- ```
957
-
958
- ## Flush data
959
- Data associated with the current user via `addData()` is not immediately sent to the server. It is stored and accumulated until it is sent automatically by the `triggerExperiment()` or `trackConversion()`, or manually by the `flush()` callback function. This allows the developer to control exactly when the data is flushed to servers. For instance, if you call the `addData()` a dozen times, it would be a waste of resources to send data to the server after each `addData()` invocation. Just call `flush()` once at the end.
960
-
961
- The `flush()` callback function is non-blocking as the server call is made asynchronously.
962
-
963
- #### `flush()`
964
- ##### Arguments
965
- - `visitorCode: string` - unique identifier of the user.
966
-
967
- ### `useFlush`
968
- #### Returns
969
- - A callback function `flush()`.
970
-
971
- #### Example
972
- ```jsx
973
- import { useEffect } from 'react';
974
- import {
975
- useAddData,
976
- useBrowser,
977
- useVisitorCode,
978
- useFlush,
979
- Browser
980
- } from '@kameleoon/react-sdk';
981
-
982
- function MyComponent(): JSX.Element {
983
- const { getVisitorCode } = useVisitorCode();
984
- const { addData } = useAddData();
985
- const { addBrowser } = useBrowser();
986
- const { flush } = useFlush();
987
-
988
- useEffect(() => {
989
- const visitorCode = getVisitorCode('example.com');
990
-
991
- addData(visitorCode, addBrowser(Browser.Chrome));
992
- flush(visitorCode);
993
- }, []);
994
-
995
- ...
996
- }
997
- ```
998
-
999
- ### `withFlush`
1000
- #### Arguments
1001
- - `Component: React.Component` - component which will be enhanced with the prop `flush()`.
1002
-
1003
- #### Returns
1004
- - A wrapped component with additional props as described above.
1005
-
1006
- #### Example
1007
- ```jsx
1008
- import {
1009
- withVisitorCode,
1010
- withAddData,
1011
- withBrowser,
1012
- withFlush,
1013
- Browser,
1014
- compose,
1015
- } from '@kameleoon/react-sdk';
1016
-
1017
- class MyComponent extends React.Component {
1018
- componentDidMount() {
1019
- const { addData, addBrowser, flush, getVisitorCode } = this.props;
1020
- const visitorCode = getVisitorCode('example.com');
1021
-
1022
- addData(visitorCode, addBrowser(Browser.Chrome));
1023
- flush(visitorCode);
1024
- }
1025
-
1026
- ...
1027
- }
1028
-
1029
- export default compose(
1030
- withAddData,
1031
- withBrowser,
1032
- withFlush,
1033
- withVisitorCode,
1034
- )(MyComponent);
1035
- ```
1036
-
1037
- ## Run when ready
1038
- In certain scenarios when working with Kameleoon API it's important to make sure that the client was initialized properly within the certain timeout. It's especially important while using `triggerExperiment()` or `trackConversion()`. For these cases it's possible to use `runWhenReady()` function, retrieved by `useRunWhenReady` hook or `withRunWhenReady` high-order component.
1039
-
1040
- The `runWhenReady()` function makes sure that Kameleoon Client will be initialized properly using HTTP call withing the specified timeout.
1041
-
1042
- #### `runWhenReady()`
1043
- ##### Arguments
1044
- - `successCallback: () => void` - callback which will be executed on successful client initialization.
1045
- - `errorCallback: () => void` - callback which will be executed if client wasn't able to initialize during the timeout.
1046
- - `timeout?: number` - timeout which is given to perform HTTP call for initialization in ms (by default: 2000 ms).
1047
-
1048
- #### Example
1049
- ```jsx
1050
- import { useEffect, useCallback, useState } from 'react';
1051
- import { useRunWhenReady, useTriggerExperiment } from '@kameleoon/react-sdk';
1052
-
1053
- function MyComponent(): JSX.Element {
1054
- const { runWhenReady } = useRunWhenReady();
1055
- const { getVariationId } = useTriggerExperiment();
1056
-
1057
- const [variationId, setVariationId] = useState<number>(0);
1058
-
1059
- const getVariationSuccessCallback = useCallback(() => {
1060
- const id = getVariationId('user_id', 12345);
1061
- setVariationId(id);
1062
- }, [getVariationId, isRenderProps]);
1063
-
1064
- const getVariationErrorCallback = useCallback(() => {
1065
- throw new Error(
1066
- "Couldn't get server configuration from HTTP request in a specified time",
1067
- );
1068
- }, []);
1069
-
1070
- useEffect(() => {
1071
- runWhenReady(
1072
- getVariationSuccessCallback,
1073
- getVariationErrorCallback,
1074
- 1000,
1075
- );
1076
- }, [runWhenReady, getVariationSuccessCallback, getVariationErrorCallback]);
1077
-
1078
- ...
1079
- }
1080
- ```
1081
-
1082
- ### `withRunWhenReady`
1083
- #### Arguments
1084
- - `Component: React.Component` - component which will be enhanced with the prop `runWhenReady()`.
1085
-
1086
- #### Example
1087
- ```jsx
1088
- import { useEffect, useCallback, useState } from 'react';
1089
- import { withRunWhenReady, withTriggerExperiment } from '@kameleoon/react-sdk';
1090
-
1091
- class MyComponent extends React.Component {
1092
- variationSuccessCallback(): void {
1093
- const id = this.props.getVariationId('user_id', 12345);
1094
- setVariationId(id);
1095
- }
12
+ - [Installation](#installation)
13
+ - [Configuration](#configuration)
1096
14
 
1097
- variationErrorCallback(): void {
1098
- const id = this.props.getVariationId('user_id', 12345);
1099
- setVariationId(id);
1100
- }
1101
-
1102
- componentDidMount() {
1103
- this.props.runWhenReady(this.variationSuccessCallback, this.variationErrorCallback, 1000);
1104
- }
1105
-
1106
- ...
1107
- }
1108
-
1109
- export default compose(
1110
- withRunWhenReady,
1111
- withTriggerExperiment,
1112
- )(MyComponent);
1113
- ```
1114
-
1115
- #### Returns
1116
- - A wrapped component with additional props as described above.
1117
-
1118
- ## Browser
1119
- A callback function `addBrowser()` adds browser type.
1120
-
1121
- #### `addBrowser`
1122
- ##### Arguments
1123
- - `browser: Browser` - browser types: CHROME, INTERNET_EXPLORER, FIREFOX, SAFARI, OPERA, OTHER.
1124
-
1125
- ##### Returns
1126
- - An instance of `Browser: IBrowser`.
1127
-
1128
- ### `useBrowser`
1129
- #### Returns
1130
- - A callback function `addBrowser()`.
1131
-
1132
- #### Example
1133
- ```jsx
1134
- import { useEffect } from 'react';
1135
- import { useAddData, useBrowser, useVisitorCode, Browser } from '@kameleoon/react-sdk';
1136
-
1137
- function MyComponent(): JSX.Element {
1138
- const { addData } = useAddData();
1139
- const { getVisitorCode } = useVisitorCode();
1140
- const { addBrowser } = useBrowser();
1141
-
1142
- useEffect(() => {
1143
- const visitorCode = getVisitorCode('example.com');
1144
-
1145
- addData(visitorCode, addBrowser(Browser.Chrome));
1146
- }, []);
1147
-
1148
- ...
1149
- }
1150
- ```
15
+ ## Installation
1151
16
 
1152
- ### `withBrowser`
1153
- #### Arguments
1154
- - `Component: React.Component` - component which will be enhanced with the prop `addBrowser()`.
17
+ - **npm** - `npm install @kameleoon/react-sdk`
18
+ - **yarn** - `yarn add @kameleoon/react-sdk`
19
+ - **pnpm** - `pnpm add @kameleoon/react-sdk`
1155
20
 
1156
- #### Returns
1157
- - A wrapped component with additional props as described above.
21
+ ## Configuration
1158
22
 
1159
- #### Example
1160
- ```jsx
1161
- import {
1162
- withVisitorCode,
1163
- withAddData,
1164
- withBrowser,
1165
- Browser,
1166
- compose,
1167
- } from '@kameleoon/react-sdk';
23
+ 1. Obtain your site code from [Kameleoon Platform](https://app.kameleoon.com/)
24
+ 2. Create client and pass it to `KameleoonProvider`
1168
25
 
1169
- class MyComponent extends React.Component {
1170
- componentDidMount() {
1171
- const { addData, addBrowser, getVisitorCode } = this.props;
1172
- const visitorCode = getVisitorCode('example.com');
26
+ ```tsx
27
+ import { createClient, KameleoonProvider } from '@kameleoon/react-sdk';
1173
28
 
1174
- addData(visitorCode, addBrowser(Browser.Chrome));
1175
- }
29
+ const client = createClient('my_site_code');
1176
30
 
1177
- ...
31
+ function MyComponentWrapper(): JSX.Element {
32
+ return (
33
+ <KameleoonProvider client={client}>
34
+ <MyComponent />
35
+ </KameleoonProvider>
36
+ );
1178
37
  }
1179
-
1180
- export default compose(
1181
- withAddData,
1182
- withBrowser,
1183
- withVisitorCode,
1184
- )(MyComponent);
1185
38
  ```
1186
39
 
1187
- ## PageView
1188
- A callback function `addPageView()` adds page view.
1189
-
1190
- #### `addPageView`
1191
- ##### Arguments
1192
- - `url: string` - URL of the page viewed.
1193
- - `title: string` - title of the page viewed.
1194
- - `referrer: number` (optional) - referrer of the page viewed.
40
+ 3. Asynchronously initialize client to fetch the configuration from remote server and handle possible errors
1195
41
 
1196
- ##### Returns
1197
- - An instance of `PageView: IPageView`.
1198
- ### `usePageView`
1199
- #### Returns
1200
- - A callback function `addPageView()`.
1201
-
1202
- #### Example
1203
- ```jsx
42
+ ```tsx
1204
43
  import { useEffect } from 'react';
1205
- import { useAddData, usePageView, useVisitorCode } from '@kameleoon/react-sdk';
1206
-
1207
- function MyComponent(): JSX.Element {
1208
- const { addData } = useAddData();
1209
- const { getVisitorCode } = useVisitorCode();
1210
- const { addPageView } = usePageView();
1211
-
1212
- useEffect(() => {
1213
- const visitorCode = getVisitorCode('example.com');
1214
-
1215
- addData(visitorCode, addPageView('example.com', 'title', 3));
1216
- }, []);
1217
-
1218
- ...
1219
- }
1220
- ```
1221
-
1222
- ### `withPageView`
1223
- #### Arguments
1224
- - `Component: React.Component` - component which will be enhanced with the prop `addPageView()` which recieves the following arguments and returns instance of `PageView: IPageView`.
1225
- - `url: string` - URL of the page viewed.
1226
- - `title: string` - title of the page viewed.
1227
- - `referrer: number` (optional) - referrer of the page viewed.
1228
-
1229
- #### Returns
1230
- - A wrapped component with additional props as described above.
1231
-
1232
- #### Example
1233
- ```jsx
1234
44
  import {
1235
- withVisitorCode,
1236
- withAddData,
1237
- withPageView,
1238
- compose,
45
+ useInitialize,
46
+ getBrowserVisitorCode,
47
+ useFeatureFlagActive,
1239
48
  } from '@kameleoon/react-sdk';
1240
49
 
1241
- class MyComponent extends React.Component {
1242
- componentDidMount() {
1243
- const { addData, addPageView, getVisitorCode } = this.props;
1244
- const visitorCode = getVisitorCode('example.com');
1245
-
1246
- addData(visitorCode, addPageView('example.com', 'title', 3));
1247
- }
1248
-
1249
- ...
1250
- }
1251
-
1252
- export default compose(
1253
- withAddData,
1254
- withPageView,
1255
- withVisitorCode,
1256
- )(MyComponent);
1257
- ```
1258
-
1259
- ## Conversion
1260
- A callback function `addConversion()` adds conversion.
1261
-
1262
- #### `addConversion`
1263
- ##### Arguments
1264
- - `goalId: number` - unique identifier of the goal.
1265
- - `revenue: number` (optional) - coversion revenue.
1266
- - `negative: boolean` (optional) - defines if the revenue is positive or negative.
1267
-
1268
- ##### Returns
1269
- - An instance of `Conversion: IConversion`.
1270
-
1271
- ### `useConversion`
1272
- #### Returns
1273
- - A callback function `addConversion()`.
1274
-
1275
- #### Example
1276
- ```jsx
1277
- import { useEffect } from 'react';
1278
- import { useAddData, useConversion, useVisitorCode } from '@kameleoon/react-sdk';
1279
-
1280
50
  function MyComponent(): JSX.Element {
1281
- const { addData } = useAddData();
1282
- const { getVisitorCode } = useVisitorCode();
1283
- const { addConversion } = useConversion();
1284
-
1285
- useEffect(() => {
1286
- const visitorCode = getVisitorCode('example.com');
1287
-
1288
- addData(visitorCode, addConversion(32, 10, false));
1289
- }, []);
51
+ const { initialize } = useInitialize();
52
+ const { getBrowserVisitorCode } = useBrowserVisitorCode();
53
+ const { isFeatureFlagActive } = useFeatureFlagActive();
1290
54
 
1291
- ...
1292
- }
1293
- ```
1294
-
1295
- ### `withConversion`
1296
- #### Arguments
1297
- - `Component: React.Component` - component which will be enhanced with the prop `addConversion()`.
1298
-
1299
- #### Returns
1300
- - A wrapped component with additional props as described above.
55
+ async function waitForInitialize(): Promise<void> {
56
+ const isReady = await initialize();
1301
57
 
1302
- #### Example
1303
- ```jsx
1304
- import {
1305
- withVisitorCode,
1306
- withAddData,
1307
- withConversion,
1308
- compose,
1309
- } from '@kameleoon/react-sdk';
58
+ if (isReady) {
59
+ const visitorCode = getBrowserVisitorCode('www.example.com');
1310
60
 
1311
- class MyComponent extends React.Component {
1312
- componentDidMount() {
1313
- const { addData, addConversion, getVisitorCode } = this.props;
1314
- const visitorCode = getVisitorCode('example.com');
1315
-
1316
- addData(visitorCode, addConversion(32, 10, false));
61
+ // -- Check if the feature is active for visitor
62
+ const isMyFeatureActive = isFeatureFlagActive(
63
+ visitorCode,
64
+ 'my_feature_key',
65
+ );
66
+ }
1317
67
  }
1318
68
 
1319
- ...
1320
- }
1321
-
1322
- export default compose(
1323
- withAddData,
1324
- withConversion,
1325
- withVisitorCode,
1326
- )(MyComponent);
1327
- ```
1328
-
1329
- ## CustomData
1330
- A callback function `addCustomData()` adds custom data.
1331
-
1332
- ##### Please Note:
1333
- _The index (ID) of the custom data is available on our Back-Office, in the Custom data configuration page. Be careful: this index starts at **0**, so the first custom data you create for a given site will have the ID **0**, **not 1**._
1334
-
1335
- #### `addCustomData`
1336
- ##### Arguments
1337
- - `index: number` - index or unique identifier of the custom data to be stored.
1338
- - `value: string` - value of the custom data to be stored.
1339
-
1340
- ##### Returns
1341
- - An instance of `CustomData: ICustomData`.
1342
-
1343
- ### `useCustomData`
1344
- #### Returns
1345
- - A callback function `addCustomData()`.
1346
-
1347
-
1348
- #### Example
1349
- ```jsx
1350
- import { useEffect } from 'react';
1351
- import { useAddData, useCustomData, useVisitorCode } from '@kameleoon/react-sdk';
1352
-
1353
- function MyComponent(): JSX.Element {
1354
- const { addData } = useAddData();
1355
- const { getVisitorCode } = useVisitorCode();
1356
- const { addCustomData } = useCustomData();
1357
-
1358
69
  useEffect(() => {
1359
- const visitorCode = getVisitorCode('example.com');
1360
-
1361
- addData(visitorCode, addCustomData(1, 'some custom value'));
70
+ waitForInitialize();
1362
71
  }, []);
1363
-
1364
- ...
1365
72
  }
1366
73
  ```
1367
74
 
1368
- ### `withCustomData`
1369
- #### Arguments
1370
- - `Component: React.Component` - component which will be enhanced with the prop `addCustomData()`.
1371
-
1372
- #### Returns
1373
- - A wrapped component with additional props as described above.
75
+ 4. `hooks` are ready to use. Note: They can be used only inside `KameleoonProvider`
1374
76
 
1375
- #### Example
1376
- ```jsx
77
+ ```tsx
1377
78
  import {
1378
- withVisitorCode,
1379
- withAddData,
1380
- withCustomData,
1381
- compose,
79
+ useAddData,
80
+ useBrowserVisitorCode,
81
+ useTriggerExperiment,
82
+ useFeatureFlagActive,
1382
83
  } from '@kameleoon/react-sdk';
1383
84
 
1384
- class MyComponent extends React.Component {
1385
- componentDidMount() {
1386
- const { addData, addCustomData, getVisitorCode } = this.props;
1387
- const visitorCode = getVisitorCode('example.com');
1388
-
1389
- addData(visitorCode, addCustomData(1, 'some custom value'));
1390
- }
1391
-
1392
- ...
1393
- }
1394
-
1395
- export default compose(
1396
- withAddData,
1397
- withCustomData,
1398
- withVisitorCode,
1399
- )(MyComponent);
1400
- ```
1401
-
1402
- ## Device
1403
- A callback function `addDevice()` adds device.
1404
-
1405
- #### `addDevice`
1406
- ##### Arguments
1407
- - `device: DeviceType` - device type: Phone, Tablet, Desktop.
1408
-
1409
-
1410
- ##### Returns
1411
- - An instance of `Device: IDevice`.
1412
-
1413
- ### `useDevice`
1414
- #### Returns
1415
- - A callback function `addDevice()`.
1416
-
1417
- #### Example
1418
- ```jsx
1419
- import { useEffect } from 'react';
1420
- import { useAddData, useDevice, DeviceType, useVisitorCode } from '@kameleoon/react-sdk';
1421
-
1422
85
  function MyComponent(): JSX.Element {
1423
86
  const { addData } = useAddData();
1424
- const { getVisitorCode } = useVisitorCode();
1425
- const { addDevice } = useDevice();
1426
-
1427
- useEffect(() => {
1428
- const visitorCode = getVisitorCode('example.com');
1429
-
1430
- addData(visitorCode, addDevice(DeviceType.Desktop));
1431
- }, []);
1432
-
1433
- ...
1434
- }
1435
- ```
1436
-
1437
- ### `withDevice`
1438
- #### Arguments
1439
- - `Component: React.Component` - component which will be enhanced with the prop `addDevice()`.
87
+ // -- Hook to generate new visitorCode. For React Native use `useNativeVisitorCode` hook
88
+ const { getBrowserVisitorCode } = useBrowserVisitorCode();
89
+ const { triggerExperiment } = useTriggerExperiment();
90
+ const { isFeatureFlagActive } = useFeatureFlagActive();
1440
91
 
1441
- #### Returns
1442
- - A wrapped component with additional props as described above.
92
+ const visitorCode = getBrowserVisitorCode('www.example.com');
93
+ const experimentId = 100;
94
+ const customDataIndex = 0;
1443
95
 
1444
- #### Example
1445
- ```jsx
1446
- import {
1447
- withVisitorCode,
1448
- withAddData,
1449
- withDevice,
1450
- DeviceType,
1451
- compose,
1452
- } from '@kameleoon/react-sdk';
1453
-
1454
- class MyComponent extends React.Component {
1455
- componentDidMount() {
1456
- const { addData, addDevice, getVisitorCode } = this.props;
1457
- const visitorCode = getVisitorCode('example.com');
1458
-
1459
- addData(visitorCode, addDevice(DeviceType.Desktop));
1460
- }
1461
-
1462
- ...
1463
- }
1464
-
1465
- export default compose(
1466
- withAddData,
1467
- withDevice,
1468
- withVisitorCode,
1469
- )(MyComponent);
1470
- ```
1471
-
1472
- ## Helpers
1473
- ### `compose`
1474
- Composes single-argument high order components.
1475
-
1476
- #### Arguments
1477
- - `HOCs` - high order components to be composed.
1478
-
1479
- #### Returns
1480
- - A function obtained by composing the argument HOCs, which is used as single high order component wrapper.
96
+ // -- Get variation id
97
+ const variationId = triggerExperiment('my_visitor_code', experimentId);
1481
98
 
1482
- #### Example
1483
- ```jsx
1484
- import { withVisitorCode, withTriggerExperiment, compose } from '@kameleoon/react-sdk';
99
+ // -- Add targeting data
100
+ addData(visitorCode, new CustomData(customDataIndex, 'my_data'));
1485
101
 
1486
- class MyComponent extends React.Component {
1487
- componentDidMount() {
1488
- const { getVisitorCode, getVariationId } = this.props;
1489
- const visitorCode = getVisitorCode('example.com');
1490
- const experimentId = 230243;
1491
-
1492
- const variationId = getVariationId(visitorCode, experimentId);
1493
- }
1494
-
1495
- ...
102
+ // -- Check if the feature is active for visitor
103
+ const isMyFeatureActive = isFeatureFlagActive(visitorCode, 'my_feature_key');
1496
104
  }
1497
-
1498
- export default compose(withVisitorCode, withTriggerExperiment)(MyComponent);
1499
105
  ```