# Reference

## `FlagshipProvider`

Here is the full list of props available to use in the `FlagshipProvider` React component:

```
  <th style={{ textAlign: "left" }}>
    Type
  </th>

  <th style={{ textAlign: "left" }}>
    Default
  </th>

  <th style={{ textAlign: "left" }}>
    Description
  </th>
</tr>
```

```
  <td style={{ textAlign: "left" }}>
    string
  </td>

  <td style={{ textAlign: "left" }}>
    Required
  </td>

  <td style={{ textAlign: "left" }}>
    Environment id provided by Flagship.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    apiKey
  </td>

  <td style={{ textAlign: "left" }}>
    string
  </td>

  <td style={{ textAlign: "left" }}>
    Required
  </td>

  <td style={{ textAlign: "left" }}>
    Api authentication key provided by Flagship.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    decisionMode
  </td>

  <td style={{ textAlign: "left" }}>
    `DECISION-API`|`BUCKETING`|`BUCKETING_EDGE`
  </td>

  <td style={{ textAlign: "left" }}>
    `DECISION-API`
  </td>

  <td style={{ textAlign: "left" }}>
    The SDK running mode. [see `Decision Mode`](#decision-mode)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    fetchNow
  </td>

  <td style={{ textAlign: "left" }}>
    boolean
  </td>

  <td style={{ textAlign: "left" }}>
    true
  </td>

  <td style={{ textAlign: "left" }}>
    Determines whether to automatically fetch flags data when creating a new `Visitor`.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    visitorData
  </td>

  <td style={{ textAlign: "left" }}>
    object
  </td>

  <td style={{ textAlign: "left" }}>
    Required
  </td>

  <td style={{ textAlign: "left" }}>
    This is the data to identify the current visitor using your app. \*\*[See arguments](#visitordata) \*\*
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    reuseVisitorIds
  </td>

  <td style={{ textAlign: "left" }}>
    boolean
  </td>

  <td style={{ textAlign: "left" }}>
    true
  </td>

  <td style={{ textAlign: "left" }}>
    **client-side only**
    If true, the SDK will save the visitor ID and/or anonymous ID, and reuse it for the next session if `visitorId` is not set, to maintain cross-session visitor experience.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    loadingComponent
  </td>

  <td style={{ textAlign: "left" }}>
    ReactNode
  </td>

  <td style={{ textAlign: "left" }}>
    undefined
  </td>

  <td style={{ textAlign: "left" }}>
    This component will be rendered when Flagship is loading at first initialization only.
    By default, the value is` undefined`. It means it will display your app and it might display default flags value for a very short moment.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    shouldSaveInstance
  </td>

  <td style={{ textAlign: "left" }}>
    boolean
  </td>

  <td style={{ textAlign: "left" }}>
    `true`
  </td>

  <td style={{ textAlign: "left" }}>
    If true, the newly created visitor instance will be returned and saved into Flagship. Otherwise,  the newly created visitor instance won't be saved and will simply be returned.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    initialCampaigns
  </td>

  <td style={{ textAlign: "left" }}>
    object
  </td>

  <td style={{ textAlign: "left" }}>
    `undefined`
  </td>

  <td style={{ textAlign: "left" }}>
    ***Optional***
    An object containing the data received when fetching the Flagship decision API (decisionMode="API").
    Providing this property avoids the SDK from having an empty cache during first initialization.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    initialFlagsData
  </td>

  <td style={{ textAlign: "left" }}>
    array
  </td>

  <td style={{ textAlign: "left" }}>
    `undefined`
  </td>

  <td style={{ textAlign: "left" }}>
    ***Optional***
    A [set](#serializedflagmetadata)  of flag data provided to avoid the SDK from having an empty cache during the first initialization.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    onFetchFlagsStatusChanged
  </td>

  <td style={{ textAlign: "left" }}>
    function(object):void
  </td>

  <td style={{ textAlign: "left" }}>
    `undefined`
  </td>

  <td style={{ textAlign: "left" }}>
    ***Optional***
    Callback function that will be called when the fetch flags status changes.
    [see arguments](#onfetchflagsstatuschanged)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    timeout
  </td>

  <td style={{ textAlign: "left" }}>
    number
  </td>

  <td style={{ textAlign: "left" }}>
    2
  </td>

  <td style={{ textAlign: "left" }}>
    The timeout in seconds for API requests.

    Timeout can't be lower than 0 second.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    logLevel
  </td>

  <td style={{ textAlign: "left" }}>
    number
  </td>

  <td style={{ textAlign: "left" }}>
    9
  </td>

  <td style={{ textAlign: "left" }}>
    The maximum log level to display. [see`LogLevel`](#loglevel)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    logManager
  </td>

  <td style={{ textAlign: "left" }}>
    object
  </td>

  <td style={{ textAlign: "left" }}>
    Defined
  </td>

  <td style={{ textAlign: "left" }}>
    A custom implementation of the LogManager interface to receive logs from the SDK.

    The object must fill the Interface [`IFlagshipLogManager`](#iflagshiplogmanager)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    decisionApiUrl
  </td>

  <td style={{ textAlign: "left" }}>
    string
  </td>

  <td style={{ textAlign: "left" }}>
    [https://decision.flagship.io/v2](https://decision.flagship.io/v2)
  </td>

  <td style={{ textAlign: "left" }}>
    This setting can be useful if you need to simulate the API for tests such as end-to-end or if you want to move to an earlier version of the Flagship API.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    pollingInterval
  </td>

  <td style={{ textAlign: "left" }}>
    number
  </td>

  <td style={{ textAlign: "left" }}>
    5
  </td>

  <td style={{ textAlign: "left" }}>
    **Bucketing mode only**\
    The time in seconds between two bucketing polling requests.

    If 0 is given, it will only poll once at start time.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    hitDeduplicationTime
  </td>

  <td style={{ textAlign: "left" }}>
    number
  </td>

  <td style={{ textAlign: "left" }}>
    2.5
  </td>

  <td style={{ textAlign: "left" }}>
    The delay in seconds for hit deduplication. After a hit is sent, any future attempts to send the same hit will be blocked until the specified delay has expired.

    If the value is 0, no deduplication process will be applied.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    initialBucketing
  </td>

  <td style={{ textAlign: "left" }}>
    object
  </td>

  <td style={{ textAlign: "left" }}>
    undefined
  </td>

  <td style={{ textAlign: "left" }}>
    **Optional**\
    An object containing the data received when fetching the bucketing endpoint.
    Providing this object will make bucketing ready to use and the first polling will immediately check for updates.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    visitorCacheImplementation
  </td>

  <td style={{ textAlign: "left" }}>
    object
  </td>

  <td style={{ textAlign: "left" }}>
    Defined
  </td>

  <td style={{ textAlign: "left" }}>
    **Optional**\
    An object that implements the [`visitorCacheImplementation`](#visitor-cache)  interface to handle the visitor cache. [see cache management](#cache-management)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    hitCacheImplementation
  </td>

  <td style={{ textAlign: "left" }}>
    object
  </td>

  <td style={{ textAlign: "left" }}>
    Defined
  </td>

  <td style={{ textAlign: "left" }}>
    **Optional**\
    An object that implements the [`IHitCacheImplementation`](#hit-cache) , interface to manage hits cache. [see cache management](#cache-management)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    disableCache
  </td>

  <td style={{ textAlign: "left" }}>
    boolean
  </td>

  <td style={{ textAlign: "left" }}>
    false
  </td>

  <td style={{ textAlign: "left" }}>
    If set to true, hit cache and visitor cache will be disabled; otherwise, they will be enabled.. [see cache management](#cache-management)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    onSdkStatusChanged
  </td>

  <td style={{ textAlign: "left" }}>
    function(number):void
  </td>

  <td style={{ textAlign: "left" }}>
    undefined
  </td>

  <td style={{ textAlign: "left" }}>
    **Optional**\
    A callback function to be called when the SDK status has changed. [see arguments](#onsdkstatuschanged).
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    onBucketingSuccess
  </td>

  <td style={{ textAlign: "left" }}>
    function(object):void
  </td>

  <td style={{ textAlign: "left" }}>
    undefined
  </td>

  <td style={{ textAlign: "left" }}>
    **Optional**\
    A callback function to be called when the first bucketing polling succeeds. [see arguments](#onbucketingsuccess)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    onBucketingFail
  </td>

  <td style={{ textAlign: "left" }}>
    function(error):void
  </td>

  <td style={{ textAlign: "left" }}>
    undefined
  </td>

  <td style={{ textAlign: "left" }}>
    **Optional**\
    A callback function to be called when the first bucketing polling fails. [see arguments](#onbucketingfail)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    onBucketingUpdated
  </td>

  <td style={{ textAlign: "left" }}>
    function(object):void
  </td>

  <td style={{ textAlign: "left" }}>
    undefined
  </td>

  <td style={{ textAlign: "left" }}>
    **Optional**\
    A callback function to be called each time bucketing data from Flagship has been updated. [see arguments](#onbucketingupdated)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    onLog
  </td>

  <td style={{ textAlign: "left" }}>
    function(level: LogLevel, tag: string, message: string):void
  </td>

  <td style={{ textAlign: "left" }}>
    undefined
  </td>

  <td style={{ textAlign: "left" }}>
    **Optional**\
    A callback function to be called whenever the SDK needs to report a log.
    [see arguments](#onlog)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    trackingManagerConfig
  </td>

  <td style={{ textAlign: "left" }}>
    object
  </td>

  <td style={{ textAlign: "left" }}>
    defined
  </td>

  <td style={{ textAlign: "left" }}>
    Options to configure hit batching.\
    [trackingManagerConfig](#tracking-manager-config)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    onVisitorExposed
  </td>

  <td style={{ textAlign: "left" }}>
    function(object):void
  </td>

  <td style={{ textAlign: "left" }}>
    undefined
  </td>

  <td style={{ textAlign: "left" }}>
    **Optional**\
    A callback function to be called each time a flag is exposed to a visitor (i.e., when an activation hit is sent by the SDK).

    [see arguments](#onvisitorexposed)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    fetchThirdPartyData
  </td>

  <td style={{ textAlign: "left" }}>
    boolean
  </td>

  <td style={{ textAlign: "left" }}>
    false
  </td>

  <td style={{ textAlign: "left" }}>
    **Optional**\
    **Bucketing mode only**
    If true, the SDK will fetch the visitor's segment from the [universal data connector](https://developers.abtasty.com/docs/data/universal-data-connector) each time `fetchFlags` is called and append those segments in the visitor context.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    nextFetchConfig
  </td>

  <td style={{ textAlign: "left" }}>
    object
  </td>

  <td style={{ textAlign: "left" }}>
    \{ revalidate: 20 }
  </td>

  <td style={{ textAlign: "left" }}>
    **Optional**\
    In Next.js 13, you can define the time in seconds for storing SDK route cache before revalidation. [learn more](https://nextjs.org/docs/app/building-your-application/data-fetching/caching#per-request-caching)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    fetchFlagsBufferingTime
  </td>

  <td style={{ textAlign: "left" }}>
    number
  </td>

  <td style={{ textAlign: "left" }}>
    2
  </td>

  <td style={{ textAlign: "left" }}>
    **Optional**

    The delay in seconds for buffering fetch flags calls. After the SDK has fetched flags, they will be buffered for the specified delay. During this delay, any subsequent fetch flags calls will return the same flags.

    **Note:**

    If a value of 0 is given, no buffering process will be applied.

    If visitor data has changed, the buffering will be bypassed.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    disableDeveloperUsageTracking
  </td>

  <td style={{ textAlign: "left" }}>
    boolean
  </td>

  <td style={{ textAlign: "left" }}>
    false
  </td>

  <td style={{ textAlign: "left" }}>
    Determines whether to disable the collection of analytics data.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    fetchFlagsOnBucketingUpdated
  </td>

  <td style={{ textAlign: "left" }}>
    boolean
  </td>

  <td style={{ textAlign: "left" }}>
    false
  </td>

  <td style={{ textAlign: "left" }}>
    **Bucketing mode only**\
    If true, it'll automatically call fetchFlags when the bucketing file has updated.
  </td>
</tr>
```

| Attribute |
| --------- |
| envId     |

> 📘 Information
>
> * Any change to the `visitorData` prop will automatically fetch flags.
> * When the props `fetchNow` is set to true, the SDK will automatically fetch flags immediately after creating the visitor. [see more](#managing-visitor-campaigns)
> * If the props `visitorData` is null, no visitor will be initialized until it is set
> * When both `initialCampaigns` and `initialFlags` are provided, the system will disregard `initialCampaigns` and only use `initialFlags`.
> * When the SDK is running in `Bucketing mode` (decisionMode="BUCKETING"), the polling interval will restart when any of the following props change after the first render: `envId`, `apiKey`, `decisionMode`.

### visitorData

The `visitorData` prop includes the following keys

```
  <th style={{ textAlign: "left" }}>
    Type
  </th>

  <th style={{ textAlign: "left" }}>
    Default
  </th>

  <th style={{ textAlign: "left" }}>
    Description
  </th>
</tr>
```

```
  <td style={{ textAlign: "left" }}>
    string
  </td>

  <td style={{ textAlign: "left" }}>
    undefined
  </td>

  <td style={{ textAlign: "left" }}>
    ***Optional***
    Unique visitor identifier.

    If not set, it will be generated automatically.

    In **client-side**, if not specified, the id will either be automatically generated or will be the visitor id from the previous session (if `reuseVisitorIds` is set to `true`).
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    hasConsented
  </td>

  <td style={{ textAlign: "left" }}>
    boolean
  </td>

  <td style={{ textAlign: "left" }}>
    undefined
  </td>

  <td style={{ textAlign: "left" }}>
    ***Required***\
    Specifies if the visitor has consented for personal data usage.
    When set to false, some features will be deactivated and the cache will be deactivated and cleared.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    context
  </td>

  <td style={{ textAlign: "left" }}>
    object
  </td>

  <td style={{ textAlign: "left" }}>
    \{}
  </td>

  <td style={{ textAlign: "left" }}>
    ***Optional***\
    The visitor context is a dataset key/value that defines the current visitor. It is sent to Flagship for targeting purposes (use-case assignment) and to enrich reporting with Context Filters.

    Context keys must be strings, and the value types must be one of the following: number, boolean, or string.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    isAuthenticated
  </td>

  <td style={{ textAlign: "left" }}>
    boolean
  </td>

  <td style={{ textAlign: "left" }}>
    false
  </td>

  <td style={{ textAlign: "left" }}>
    **Optional**\
    Specify if the visitor is authenticated or anonymous for Experience continuity.
  </td>
</tr>
```

| key |
| --- |
| id  |

### Decision Mode

**`DECISION-API`Mode** (by default)

When the SDK operates in `API` mode, it uses our [Decision API](doc:decision-mode) to manage campaign assignments and validate targeting. In this mode, each time a new Decision is needed, the SDK sends an HTTPS request to the API. This mode is enabled by default for all our SDKs.

**`Bucketing`Mode**

In `Bucketing` mode, the SDK downloads all campaign configurations in a single bucketing file. This allows the SDK to compute variation assignments on the client-side. The bucketing file is cached and only re-downloaded when campaign configurations are updated in the Flagship interface. [**Learn more**](doc:bucketing)

`DecisionMode` is an enum defining the decision type

| Key           | Value        | Type   | Description                    |
| ------------- | ------------ | ------ | ------------------------------ |
| DECISION\_API | DECISION-API | string | Flagship SDK mode Decision API |
| BUCKETING     | BUCKETING    | string | Flagship SDK mode bucketing    |

### onLog

The `onLog` function has 3 arguments

| Argument | Type   | Description                                    |
| -------- | ------ | ---------------------------------------------- |
| level    | number | Get the log level. [see `LogLevel`](#loglevel) |
| tag      | string | Get the function that triggered the log        |
| message  | string | Get a description of the log                   |

```typescript
import { LogLevel, FlagshipProvider } from "@flagship.io/react-sdk";


const App = () => (
  <>
    <FlagshipProvider
      envId="YOUR_ENV_ID"
      apiKey="YOUR_API_KEY"
      visitorData={{
        id: 'YOUR_VISITOR_ID',
        hasConsented: true,
        context: {
          // some context
        },
      }}
        onLog={(level, tag, message) => {
          console.log(`[${LogLevel[level]}] [${tag}] : ${message}`)
        }}
    >
      {/* [...] */}
    </FlagshipProvider>
  </>
)

```

### LogLevel

LogLevel is an enum defined the level of log to receive

| Key       | Value | Type | Description                               |
| --------- | ----- | ---- | ----------------------------------------- |
| NONE      | 0     | int  | Logging will be disabled.                 |
| EMERGENCY | 1     | int  | Only emergencies will be logged           |
| ALERT     | 2     | int  | Only alerts and above will be logged.     |
| CRITICAL  | 3     | int  | Only critical and above will be logged.   |
| ERROR     | 4     | int  | Only errors and above will be logged.     |
| WARNING   | 5     | int  | Only warnings and above will be logged.   |
| NOTICE    | 6     | int  | Only notices and above will be logged.    |
| INFO      | 7     | int  | Only info logs and above will be logged.  |
| DEBUG     | 8     | int  | Only debug logs and above will be logged. |
| ALL       | 9     | int  | Everything will be logged.                |

### IFlagshipLogManager

The aims of this Interface is to define methods that an object must have in order to receive Flagship SDK logs

```typescript
interface IFlagshipLogManager {
  emergency(message: string, tag: string): void;
  alert(message: string, tag: string): void;
  critical(message: string, tag: string): void;
  error(message: string, tag: string): void;
  warning(message: string, tag: string): void;
  notice(message: string, tag: string): void;
  info(message: string, tag: string): void;
  debug(message: string, tag: string): void;
  log(level: LogLevel, message: string, tag: string): void;
}
```

```
  <th style={{ textAlign: "left" }}>
    Type
  </th>

  <th style={{ textAlign: "left" }}>
    Description
  </th>
</tr>
```

```
  <td style={{ textAlign: "left" }}>
    string
  </td>

  <td style={{ textAlign: "left" }}>
    Get a description of the log
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    tag
  </td>

  <td style={{ textAlign: "left" }}>
    string
  </td>

  <td style={{ textAlign: "left" }}>
    Get the function that triggered the log
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    level
  </td>

  <td style={{ textAlign: "left" }}>
    number
  </td>

  <td style={{ textAlign: "left" }}>
    Get the log level.

    * \*Note: *only for log method*\*\* [see `LogLevel`](#loglevel)
  </td>
</tr>
```

| Argument |
| -------- |
| message  |

### onSdkStatusChanged

The `onSdkStatusChanged` function has one argument

| Argument | Type   | Description                                         |
| -------- | ------ | --------------------------------------------------- |
| status   | number | Status of the SDK. [see`FSSdkStatus`](#fssdkstatus) |

### FSSdkStatus)

`FSSdkStatus` is an enum defining the different status of Flagship SDK

```typescript
import { FSSdkStatus } from "@flagship.io/react-sdk";

const status = FSSdkStatus.SDK_INITIALIZED;
```

```typescript
import { FSSdkStatus } from "https://deno.land/x/flagship_io_js_sdk/mod.ts";

const status = FSSdkStatus.SDK_INITIALIZED;
```

| Key                   | Value | Type | Description                                                                                                               |
| --------------------- | ----- | ---- | ------------------------------------------------------------------------------------------------------------------------- |
| SDK\_NOT\_INITIALIZED | 0     | int  | It is the default initial status. This status remains until the sdk has been initialized successfully.                    |
| SDK\_INITIALIZING     | 1     | int  | The SDK is currently initializing.                                                                                        |
| SDK\_PANIC            | 2     | int  | Flagship SDK is ready but is running in Panic mode: All features are disabled except the one which refreshes this status. |
| SDK\_INITIALIZED      | 3     | int  | The Initialization is done, and Flagship SDK is ready to use.                                                             |

### onBucketingSuccess

The `onBucketingSuccess` function has one argument with the following shape:

| Key/Property | Type   | Description                                                   |
| ------------ | ------ | ------------------------------------------------------------- |
| status       | number | String. Returns either 200 (fresh update) or 304 (no change). |
| payload      | object | The latest bucketing data received.                           |

### onBucketingFail

The `onBucketingFail` function has one argument

| Argument | Type   | Description                |
| -------- | ------ | -------------------------- |
| error    | object | Returns the error occurred |

### onBucketingUpdated

The `onBucketingUpdated` function has one argument

| Argument   | Type | Description                       |
| ---------- | ---- | --------------------------------- |
| lastUpdate | Date | Get the date of the latest update |

### OnVisitorExposed

In some cases, you'll need to send information about the exposure (When a flag has been seen by your visitor), like sending visitor and flag data to third parties.

To centralize it, we provide a callback in the configuration option of the SDK.

The `OnVisitorExposed` function accepts one argument with the following shape:

| Argument | Type             | Description                |
| -------- | ---------------- | -------------------------- |
| param    | OnVisitorExposed | Get data from exposed flag |

**OnVisitorExposed shape**

```typescript
type OnVisitorExposed ={
    exposedVisitor: {
      id: string
      anonymousId?:string|null
      context: Record<string, string|number|boolean>
  },
    fromFlag: {
      key: string
      value: unknown
      defaultValue: unknown
      metadata: IFSFlagMetadata
  }
}
```

```
  <th style={{ textAlign: "left" }}>
    Type
  </th>

  <th style={{ textAlign: "left" }}>
    Description
  </th>
</tr>
```

```
  <td style={{ textAlign: "left" }}>
    object
  </td>

  <td style={{ textAlign: "left" }}>
    This object represent the exposed visitor
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    fromFlag
  </td>

  <td style={{ textAlign: "left" }}>
    object
  </td>

  <td style={{ textAlign: "left" }}>
    This object represent the exposed flag.
    (The flag that has triggered the exposure)
  </td>
</tr>
```

| Key/Property   |
| -------------- |
| exposedVisitor |

**exposedVisitor** object shape

| Key/Property | Type                                     | Description     |
| ------------ | ---------------------------------------- | --------------- |
| id           | string                                   | visitor id      |
| anonomousId  | string                                   | anonymous id    |
| context      | Record\<string, string\|number\|boolean> | visitor context |

**fromFlag** object shape

| Key/Property | Type            | Description                                                     |
| ------------ | --------------- | --------------------------------------------------------------- |
| key          | string          | flag key                                                        |
| value        | unknown         | flag value                                                      |
| defaultValue | unknown         | flag default value                                              |
| metadata     | IFSFlagMetadata | Campaign information metadata [see](#ifsflagmetadata-interface) |

Here is an example on how to use this callback:

[Example with Mixpanel integration](https://docs.developers.flagship.io/docs/integrate-with-mixpanel)\
[Example with Segment integration](https://docs.developers.flagship.io/docs/integrate-with-segmentcom)

### onFetchFlagsStatusChanged

The `onFetchFlagsStatusChanged` function has one argument

| Argument | Type   | Description                                                   |
| -------- | ------ | ------------------------------------------------------------- |
| status   | number | Status of the SDK. [see`FetchFlagsStatus`](#fetchflagsstatus) |

#### **FetchFlagsStatus**

`FetchFlagsStatus` is an object representing the status of visitor fetch for flag data.

```typescript
type FetchFlagsStatus = {
  /**
   * The new status of the flags fetch.
   */
  status: FSFetchStatus;
  /**
   * The reason for fetching Flags.
   */
  reason: FSFetchReasons;
};
```

| Key/Property | Type   | Description                                                    |
| ------------ | ------ | -------------------------------------------------------------- |
| status       | object | Enum representing the status of the flags in the Flagship SDK. |
| reason       | object | Enum representing the reasons for fetching Flags.              |

**FSFetchStatus** enum

`FSFetchStatus` is an enum representing the status of the flags in the visitor instance

| Key             | Type   | Description                                                                                                     |
| --------------- | ------ | --------------------------------------------------------------------------------------------------------------- |
| FETCHED         | string | The flags have been successfully fetched from the API or re-evaluated in bucketing mode.                        |
| FETCH\_REQUIRED | string | The flags need to be re-fetched due to a change in context, or because the flags were loaded from cache or XPC. |
| NOT\_FOUND      | string | The flag was not found or does not exist.                                                                       |
| PANIC           | string | The SDK is in PANIC mode: All features are disabled except for the one to fetch flags.                          |

**FSFetchReasons** enum

`FSFetchReasons` is an enum representing the reasons for re-fetching Flags.

| Key               | Type   | Description                                                     |
| ----------------- | ------ | --------------------------------------------------------------- |
| AUTHENTICATE      | string | Indicates that the XPC method 'authenticate' has been called.   |
| FETCH\_ERROR      | string | Indicates that fetching flags has failed.                       |
| NONE              | string | Indicates that there is no specific reason for fetching flags.  |
| READ\_FROM\_CACHE | string | Indicates that flags have been fetched from the cache.          |
| UPDATE\_CONTEXT   | string | Indicates that a context has been updated or changed.           |
| UNAUTHENTICATE    | string | Indicates that the XPC method 'unauthenticate' has been called. |
| VISITOR\_CREATED  | string | Indicates that the visitor has been created.                    |

### Tracking Manager Config

Represents the configuration for the tracking manager.

The Tracking Manager’s batch processing reduces network traffic, prevents hits loss through caching, and resends any failed hits.

**options:**

```
  <th style={{ textAlign: "left" }}>
    Type
  </th>

  <th style={{ textAlign: "left" }}>
    Default value
  </th>

  <th style={{ textAlign: "left" }}>
    Description
  </th>
</tr>
```

```
  <td style={{ textAlign: "left" }}>
    CacheStrategy | number
  </td>

  <td style={{ textAlign: "left" }}>
    `CONTINUOUS_CACHING`: 0
  </td>

  <td style={{ textAlign: "left" }}>
    Define the strategy that will be used for hit caching
    [see cacheStrategy](#cachestrategy)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    poolMaxSize
  </td>

  <td style={{ textAlign: "left" }}>
    number
  </td>

  <td style={{ textAlign: "left" }}>
    `10`
  </td>

  <td style={{ textAlign: "left" }}>
    Define the minimum number of hits the pool must reach to automatically batch all hits in the pool and send them.

    The value must be greater than 5 otherwise default value will be used

    Note: Having a large poolMaxSize can lead to performance issues
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    batchIntervals
  </td>

  <td style={{ textAlign: "left" }}>
    number
  </td>

  <td style={{ textAlign: "left" }}>
    `5s`
  </td>

  <td style={{ textAlign: "left" }}>
    Define a regular interval in seconds to trigger batch process.

    The process will batch all hits from the pool whether `poolMaxSize` is reached or not

    The value must be between 1 second and 10800s (3 hours). Otherwise default value will be applied
  </td>
</tr>
```

| Key           |
| ------------- |
| cacheStrategy |

#### CacheStrategy

`cacheStrategy` is an enum defining the different caching strategies

```
  <th style={{ textAlign: "left" }}>
    Type
  </th>

  <th style={{ textAlign: "left" }}>
    value
  </th>

  <th style={{ textAlign: "left" }}>
    Description
  </th>
</tr>
```

```
  <td style={{ textAlign: "left" }}>
    number
  </td>

  <td style={{ textAlign: "left" }}>
    0
  </td>

  <td style={{ textAlign: "left" }}>
    When a hit is emitted, it will first be cached in database using [IHitCacheImplementation](#hit-cache), added into the pool, then after batching and sending, it will be flushed from database using [IHitCacheImplementation](#hit-cache).

    It is Recommended for `client side applications` and should be used when your application is running in an environment where the probability of data loss is high.

    The SDK has a default cache implementation for browser using `localStorage`

    Keep in mind that this strategy can do a lot of database I/O depending on how many hits your visitor can send.[see example using localStorage](#localstorage)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    PERIODIC\_CACHING
  </td>

  <td style={{ textAlign: "left" }}>
    number
  </td>

  <td style={{ textAlign: "left" }}>
    1
  </td>

  <td style={{ textAlign: "left" }}>
    When a hit is emitted, it will be added into the pool, then after batching and sending, all database hits will be flushed, then the entire pool will be cached using [IHitCacheImplementation](#hit-cache) for both actions.

    It is recommended for server-side applications and should be used when your application sends a lot of hits and the probability of data loss is low.

    The number of I/Os in the database is low.[see example using redis](#redis)
  </td>
</tr>
```

| Key                   |
| --------------------- |
| CONTINUOUS\\\_CACHING |

```jsx
import React from "react";
import { FlagshipProvider, CacheStrategy } from "@flagship.io/react-sdk";

const App = () => (
  <>
    <FlagshipProvider
      envId="YOUR_ENV_ID"
      apiKey="YOUR_API_KEY" 
      visitorData={{
        id: "YOUR_VISITOR_ID",
        hasConsented: true,
        context: {
          // some context
        },
        isAuthenticated: false,
      }}
      trackingManagerConfig={{
        cacheStrategy: CacheStrategy.CONTINUOUS_CACHING,
        poolMaxSize: 10,
        batchIntervals: 5
    }}
    >
      {/* [...] */}
    </FlagshipProvider>
  </>
);
```

\\

## `useFlagship` hook

This is the most frequently used hook from the Flagship React SDK. It provides additional functionalities such as retrieving the current flags of your actual visitor, sending hit tracking, checking SDK status, and more...

Returns an object. *(Typescript:`UseFlagshipOutput`)*

```
  <th style={{ textAlign: "left" }}>
    Type
  </th>

  <th style={{ textAlign: "left" }}>
    Description
  </th>
</tr>
```

```
  <td style={{ textAlign: "left" }}>
    string
  </td>

  <td style={{ textAlign: "left" }}>
    The unique visitor identifier.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    anonymousId
  </td>

  <td style={{ textAlign: "left" }}>
    string
  </td>

  <td style={{ textAlign: "left" }}>
    The anonymous visitor identifier.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    setConsent
  </td>

  <td style={{ textAlign: "left" }}>
    function(hasConsented: boolean): void
  </td>

  <td style={{ textAlign: "left" }}>
    Sets whether the visitor has consented for protected data usage. [See description](#setconsent-method) .
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    hasConsented
  </td>

  <td style={{ textAlign: "left" }}>
    boolean
  </td>

  <td style={{ textAlign: "left" }}>
    Indicates whether the visitor has consented for protected data usage.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    updateContext
  </td>

  <td style={{ textAlign: "left" }}>
    function(context: Record\<string, boolean|string|number>): void
  </td>

  <td style={{ textAlign: "left" }}>
    Update the visitor context values, matching the given keys, used for targeting.
    A new context value associated with this key will be created if there is no previous matching value.
    [See description](#updatecontext-method).
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    context
  </td>

  <td style={{ textAlign: "left" }}>
    object
  </td>

  <td style={{ textAlign: "left" }}>
    This property returns all the visitor's current context as an object
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    clearContext
  </td>

  <td style={{ textAlign: "left" }}>
    function(): void
  </td>

  <td style={{ textAlign: "left" }}>
    Clear the actual visitor context.
    [See description](#clearcontext-method).
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    fetchFlags
  </td>

  <td style={{ textAlign: "left" }}>
    function(): Promise\<void>
  </td>

  <td style={{ textAlign: "left" }}>
    Invokes the `decision API` or refers to the `bucketing file` to refresh all campaign flags based on the visitor's context.
    [See description](#fetchflags-method)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    getFlag
  </td>

  <td style={{ textAlign: "left" }}>
    function(key: string): object
  </td>

  <td style={{ textAlign: "left" }}>
    Return a [Flag](#flag-class)  object by its key. If no flag matches the given key, an empty flag will be returned. Call exists() to check if the flag has been found.
    [See description](#getflag-method)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    getFlags
  </td>

  <td style={{ textAlign: "left" }}>
    function(): object
  </td>

  <td style={{ textAlign: "left" }}>
    Returns a [collection](#ifsflagcollection)  of all flags fetched for the visitor.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    authenticate
  </td>

  <td style={{ textAlign: "left" }}>
    function(visitorId: string): void
  </td>

  <td style={{ textAlign: "left" }}>
    Authenticate anonymous visitor
    [See description](#authenticate-method)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    unauthenticate
  </td>

  <td style={{ textAlign: "left" }}>
    function(): void
  </td>

  <td style={{ textAlign: "left" }}>
    This function change authenticated Visitor to anonymous visitor.
    [See description](#unauthenticate-method)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    sdkStatus
  </td>

  <td style={{ textAlign: "left" }}>
    FSSdkStatus
  </td>

  <td style={{ textAlign: "left" }}>
    Return current status of Flagship SDK.  [see`FSSdkStatus`](#fssdkstatus)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    fetchStatus
  </td>

  <td style={{ textAlign: "left" }}>
    FetchFlagsStatus
  </td>

  <td style={{ textAlign: "left" }}>
    The fetch status of the flags. [see FetchFlagsStatus](#fetchflagsstatus)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    flagsData
  </td>

  <td style={{ textAlign: "left" }}>
    object\[]
  </td>

  <td style={{ textAlign: "left" }}>
    An array of [flag data](#flag-data-shape)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    sendHits
  </td>

  <td style={{ textAlign: "left" }}>
    function(hit: object| object\[]): Promise\<void>
  </td>

  <td style={{ textAlign: "left" }}>
    Sends a hit to the Flagship server. **[See description](#sendhits-method)**
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    close
  </td>

  <td style={{ textAlign: "left" }}>
    function(): Promise\<void>
  </td>

  <td style={{ textAlign: "left" }}>
    Most of the time you don't need to manually close the SDK, but when your application is about to terminate, you should call the `close` method of the Flagship class to avoid data loss.

    When called, it Batches and sends all hits that are in the pool before the application is closed.
  </td>
</tr>
```

| Key/Property |
| ------------ |
| visitorId    |

### `setConsent` method

Sets whether the visitor has consented for protected data usage.

* **`setConsent(hasConsented: boolean): void`**

It accepts one argument:

| Argument     | Type    | Default  | Description                                                                               |
| ------------ | ------- | -------- | ----------------------------------------------------------------------------------------- |
| hasConsented | boolean | required | Set visitor consent for private data usage. When false some features will be deactivated. |

### `updateContext` method

Update the visitor context values, matching the given keys, used for targeting.\
\
A new context value associated with this key will be created if there is no previous matching value.

* **`public updateContext(context: Record<string, string | number | boolean>): void`**

It has one argument :

| Argument | Type   | Description            |
| -------- | ------ | ---------------------- |
| context  | object | A Set of keys, values. |

### `clearContext` method

Clear the actual visitor context

* **`clearContext(): void`**

> 🚧
>
> * Visitor context keys must have a type of `string`
> * Visitor context values must have a type of `string`, `bool`, `numeric`
> * Visitor context keys and values are **case sensitive**
> * Whenever you update visitor context, the SDK automatically re-fetches flags based on the updated context.

### Context with predefined keys of context

Here's an example of how to use these predefined keys to update the visitor context in both Node.js and Deno environments:

```jsx
import React from "react";
import { FlagshipProvider, DEVICE_LOCALE } from "@flagship.io/react-sdk";

const App = () => (
  <>
    <FlagshipProvider
      envId="YOUR_ENV_ID"
      apiKey="YOUR_API_KEY"
      visitorData={{
        hasConsented: true,
        context: {
          [DEVICE_LOCALE]: "fr",
        },
      }}
    >
      {/* [...] */}
    </FlagshipProvider>
  </>
);
```

```jsx
import React from "react";
import { useFlagship } from "@flagship.io/react-sdk";

export const MyReactComponent = () => {
  const { updateContext } = useFlagship()
  
  return (
    <button
    	onClick={()=>{
        updateContext({
          [DEVICE_LOCALE]: "fr"
        })
      }}>
      Trigger update context
    </button>
  );
};
```

[Here](#predefined-visitor-context-keys) is the List of all predefined context keys.

### `fetchFlags` method

Invokes the `decision API` or refers to the `bucketing file` to refresh all campaign flags based on the visitor's context.

* **`fetchFlags(): Promise<void>`**

### `getFlag` method

Return a [Flag](#flag-class) object by its key. If no flag matches the given key, an empty flag will be returned. the `exists()` method of the [Flag](#flag-class) object can be called to check if the flag has been found.

* **`getFlag(key:string):IFlag`**

Arguments:

| Name | Type   | Description                     |
| ---- | ------ | ------------------------------- |
| key  | String | The key associated to the flag. |

### `getFlags` method

Returns a [collection](#ifsflagcollection) of all flags fetched for the visitor.

* **`getFlags(): IFSFlagCollection`**

### `authenticate` method

Authenticate anonymous visitor

* **`authenticate(visitorId: string): void`**

| Argument  | Type   | Default  | Description                          |
| --------- | ------ | -------- | ------------------------------------ |
| visitorId | string | required | id of the new authenticated visitor. |

> 📘 Information
>
> * Whenever the `authenticate` method is called, the SDK automatically re-fetches flags.
> * The visitor targeting / Flags could change based on this new data.

### `unauthenticate` method

This function change authenticated Visitor to anonymous visitor

* **`unauthenticate(): void`**

> 📘 Information
>
> * Whenever the `unauthenticate` method is called, the SDK automatically re-fetches flags.
> * The visitor targeting / Flags could change based on this new data.

### `sendHits` method

This method Sends a hit or multiple hits to the Flagship server.

* **`send (hits: IHit| IHit[]): Promise<void>`**

Parameter:

| name | Type   | Default  | Description                    |
| ---- | ------ | -------- | ------------------------------ |
| hits | object | required | Hits to send. [see Hit](#page) |

\\

## `useFsFlag` hook

> 📘 Shortcut hook
>
> The purpose of this hook is to rapidly get a flag.

This hook returns a [Flag](#flag-class-api) object by its key. If no flag matches the given key an empty flag will be returned.

* **`useFsFlag<T>(key: string) : IFlag<T>`**

| Argument | Type   | Description                 |
| -------- | ------ | --------------------------- |
| key      | String | key associated to the flag. |

\\

## `IFSFlag` interface

This interface represents a flag in the `Flagship SDK`. It helps you retrieve the flag value, access flag metadata, expose the flag, verify the flag's existence, and get the flag status with the following API:

### `metadata` property

It returns an object that implements the [IFSFlagMetadata](#ifsflagmetadata-interface) interface, which contains the metadata of the campaign’s flag. If the flag doesn’t exist, it returns an empty object.

* **`metadata:IFSFlagMetadata`**

### `status` property

Return the flag status.

* **`status: FSFlagStatus`**

`FSFlagStatus` is an enum representing the status of the flag

| Key             | Type   | Description                                                                                                     |
| --------------- | ------ | --------------------------------------------------------------------------------------------------------------- |
| FETCHED         | string | The flags have been successfully fetched from the API or re-evaluated in bucketing mode.                        |
| FETCH\_REQUIRED | string | The flags need to be re-fetched due to a change in context, or because the flags were loaded from cache or XPC. |
| NOT\_FOUND      | string | The flag was not found or does not exist.                                                                       |
| PANIC           | string | The SDK is in PANIC mode: All features are disabled except for the one to fetch flags.                          |

### `getValue` method

Returns the value of the flag if the flag exists and the type of the default value matches the flag type value, otherwise it returns the default value.

* **`getValue<T>(defaultValue: T, visitorExposed : boolean) : T`**

Argument:

```
  <th style={{ textAlign: "left" }}>
    Type
  </th>

  <th style={{ textAlign: "left" }}>
    Default Value
  </th>

  <th style={{ textAlign: "left" }}>
    Description
  </th>
</tr>
```

```
  <td style={{ textAlign: "left" }}>
    T
  </td>

  <td style={{ textAlign: "left" }}>
    `Required`
  </td>

  <td style={{ textAlign: "left" }}>
    * \*Required\*\*The default value of the flag.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    visitorExposed
  </td>

  <td style={{ textAlign: "left" }}>
    Boolean
  </td>

  <td style={{ textAlign: "left" }}>
    true
  </td>

  <td style={{ textAlign: "left" }}>
    Indicates to Flagship that the visitor have been exposed and have seen this flag. This will increment the visits for the current variation on your campaign reporting.\
    It is possible to set this param to false and call `visitorExposed()` afterward when the visitor sees it.
  </td>
</tr>
```

| Name         |
| ------------ |
| defaultValue |

> 📘 Information
>
> * The default value must be one of the following type : `string`, `number`, `boolean`, `object`, `array` or `null`.
> * When the default value is `null`, no type checking will be performed

### `visitorExposed` method

Notifies Flagship that the visitor has been exposed to and seen this flag.

* **`visitorExposed(): Promise<void>`**

### `exists` method

This method checks if the flag exists.

* **`exists(): boolean`**

\\

## `IFSFlagCollection` interface

It represents a collection of flags.

### `size` property

Gets the number of flags in the collection.

* **`readonly size: number`**

### `get` method

It returns the [flag](#ifsflag-interface) associated with the specified key, or an empty if the key is not found.

* **`get(key: string): IFSFlag`**

Arguments:

| Name | Type   | Description                     |
| ---- | ------ | ------------------------------- |
| key  | String | The key associated to the flag. |

### `has` method

Checks if the collection contains a flag with the specified key.

* **`has(key: string): boolean`**

Arguments:

| Name | Type   | Description                     |
| ---- | ------ | ------------------------------- |
| key  | String | The key associated to the flag. |

### `keys` method

Gets the keys of all flags in the collection.

* **`keys(): Set<string>`**

### `filter` method

It filters the collection based on a predicate function and returns A new [IFSFlagCollection](#ifsflagcollection-interface) containing the flags that satisfy the predicate.

* **`filter(predicate: (value: IFSFlag, key: string, collection: IFSFlagCollection) => boolean): IFSFlagCollection;`**

Arguments:

| Name      | Type     | Description                                           |
| --------- | -------- | ----------------------------------------------------- |
| predicate | function | The predicate function used to filter the collection. |

### `exposeAll` method

Exposes all flags in the collection.

* **`exposeAll(): Promise<void>`**

### `getMetadata` method

A map containing the [metadata](#ifsflagmetadata-interface) for all [flags](#ifsflag-interface) in the collection.

* **`getMetadata(): Map<string, IFSFlagMetadata>;`**

### `toJSON` method

Serializes the [metadata](#ifsflagmetadata-interface) for all flags in the collection.

* **`toJSON(): SerializedFlagMetadata[]`**

### `forEach` method

Iterates over each flag in the collection.

* **`forEach (callbackfn: (value: IFSFlag, key: string, collection: IFSFlagCollection) => void): void`**

\\

## `IFSFlagMetadata` interface

```typescript
interface IFSFlagMetadata{
    campaignId:string
  	campaignName:string
    variationGroupId:string
  	variationGroupName:string
    variationId: string
  	variationName:string
    isReference: boolean
    campaignType: string
    slug?:string|null
}
```

| Key                | Type    | Description                              |
| ------------------ | ------- | ---------------------------------------- |
| campaignId         | string  | Campaign ID                              |
| campaignName       | string  | Campaign name                            |
| variationGroupId   | string  | Variation group ID                       |
| variationGroupName | string  | Variation group Name                     |
| variationId        | string  | The variation ID assigned to the visitor |
| variationName      | string  | Variation name                           |
| isReference        | boolean | Specify if its the reference variation   |
| campaignType       | string  | campaign type                            |
| slug               | string  | campaign slug                            |

## SerializedFlagMetadata

| Key                | Type    | Description                              |
| ------------------ | ------- | ---------------------------------------- |
| key                | string  | Flag name                                |
| campaignId         | string  | Campaign ID                              |
| campaignName       | string  | Campaign name                            |
| slug               | string  | campaign slug                            |
| campaignType       | string  | campaign type                            |
| variationGroupId   | string  | Variation group ID                       |
| variationGroupName | string  | Variation group name                     |
| variationId        | string  | The variation ID assigned to the visitor |
| variationName      | string  | Variation name                           |
| isReference        | boolean | Specify if its the reference variation   |
| hex                | string  | Reserved for Flagship                    |

\\

## Hit Tracking

This section guides you on how to track visitors in your application and learn how to build hits to feed your reports. For more details about our measurement protocol, refer to our [Universal Collect documentation](doc:universal-collect-documentation).

There are five different types of Hits:

* Page
* Screen
* Transaction
* Item
* Event

### HitType

```jsx
import React from "react";
import { useFlagship, HitType } from "@flagship.io/react-sdk";

export const MyReactComponent = () => {
  const pageHit = {
    type: HitType.PAGE,
    documentLocation: "https://localhost",
  }
  
  return (
    <>...</>
  );
};
```

| Key         | type   | Value       | Description                                         |
| ----------- | ------ | ----------- | --------------------------------------------------- |
| PAGE        | string | PAGEVIEW    | Indicates a URL viewed by a visitor.                |
| SCREEN      | string | SCREENVIEW  | Indicates a screen viewed by a visitor.             |
| TRANSACTION | string | TRANSACTION | Indicates a transaction made by a visitor.          |
| ITEM        | string | ITEM        | Represents an item purchased in a transaction.      |
| EVENT       | string | EVENT       | Indicates a specific action performed by a visitor. |

### Common Optional Parameters for Hits

```jsx
import React from "react";
import { useFlagship, HitType } from "@flagship.io/react-sdk";

export const MyReactComponent = () => {
  const fs = useFlagship()
  
  return (
    <button
      onClick={()=>{
        fs.sendHits({
          documentLocation: "https://localhost",
          userIp: "127.0.0.1",
          screenResolution: "800X600",
          locale: "fr",
          sessionNumber: "1234"
        })
      }}>
      Send a hit
    </button>
  );
};
```

| Parameter        | Type   | Description                     |
| ---------------- | ------ | ------------------------------- |
| userIp           | String | (Optional) Visitor's IP address |
| screenResolution | string | (Optional) Screen resolution.   |
| locale           | String | (Optional) Visitor's language   |
| sessionNumber    | string | (Optional) Session number       |

### Page hit

This hit should be sent each time a visitor navigates to a new page.

It has the following structure:

| Key/Property     | Type                | Default  | Description                          |
| ---------------- | ------------------- | -------- | ------------------------------------ |
| type             | string (`PAGEVIEW`) | required | type of hit. [see HitType](#hittype) |
| documentLocation | String              | required | Valid url.                           |

### Screen hit

This hit should be sent each time a visitor navigates to a new interface on the client side.

It has the following structure:

| Key/Property     | Type                  | Default  | Description                          |
| ---------------- | --------------------- | -------- | ------------------------------------ |
| type             | string (`SCREENVIEW`) | required | Type of hit. [see HitType](#hittype) |
| documentLocation | String                | required | Name of screen.                      |

### Transaction hit

This hit should be sent when a visitor completes a Transaction.

It has this following structure:

| Key/Property   | Type                   | Default  | Description                                                                                                                                                  |
| -------------- | ---------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| type           | string (`TRANSACTION`) | required | Type of hit. [see HitType](#hittype)                                                                                                                         |
| transactionId  | String                 | required | Unique identifier for your transaction.                                                                                                                      |
| affiliation    | String                 | required | The name of the KPI that you will have inside your reporting. [**Learn more**](https://github.com/flagship-io/Gitbook/blob/main/docs/glossary/README.md#kpi) |
| totalRevenue   | float                  | optional | The total revenue associated with the transaction, including any shipping and/or tax amounts.                                                                |
| shippingCosts  | float                  | optional | The total shipping cost of your transaction.                                                                                                                 |
| shippingMethod | String                 | optional | The shipping method for your transaction.                                                                                                                    |
| taxes          | float                  | optional | Specifies the total amount of taxes in your transaction.                                                                                                     |
| currency       | String                 | optional | Specifies the currency of your transaction. NOTE: This value should be a valid ISO 4217 currency code.                                                       |
| paymentMethod  | String                 | optional | Specifies the payment method used for your transaction.                                                                                                      |
| itemCount      | int                    | optional | Specifies the number of items in your transaction.                                                                                                           |
| couponCode     | String                 | optional | Specifies the coupon code used by the customer in your transaction.                                                                                          |

### Item hit

This hit is used to associate an item with a transaction. It should be sent following the corresponding transaction hit.

It has this following structure:

| Key/Property  | Type            | Default  | Description                              |
| ------------- | --------------- | -------- | ---------------------------------------- |
| type          | string (`ITEM`) | required | Type of hit. [see HitType](#hittype)     |
| transactionId | String          | required | Unique identifier for your transaction.  |
| productName   | String          | required | Name of your item.                       |
| productSku    | String          | required | SKU or item code.                        |
| itemCategory  | String          | optional | Category to which the item belongs.      |
| itemPrice     | float           | optional | Price for a single item/unit.            |
| itemQuantity  | int             | optional | Specifies the number of items purchased. |

> 📘 Information
>
> The `Item` hit is not currently available in the Flagship reporting view.

### Event hit

This hit can be used to track any event, such as a click on 'Add To Cart' or a newsletter subscription.

It has the following structure:

```
  <th style={{ textAlign: "left" }}>
    Type
  </th>

  <th style={{ textAlign: "left" }}>
    Default
  </th>

  <th style={{ textAlign: "left" }}>
    Description
  </th>
</tr>
```

```
  <td style={{ textAlign: "left" }}>
    string (`EVENT`)
  </td>

  <td style={{ textAlign: "left" }}>
    required
  </td>

  <td style={{ textAlign: "left" }}>
    Type of hit. [see HitType ](#hittype)
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    category
  </td>

  <td style={{ textAlign: "left" }}>
    string
  </td>

  <td style={{ textAlign: "left" }}>
    required
  </td>

  <td style={{ textAlign: "left" }}>
    Category of your event.

    * \*NOTE:**This value must be either**`User Engagement`**or**`Action Tracking`\*\*.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    action
  </td>

  <td style={{ textAlign: "left" }}>
    string
  </td>

  <td style={{ textAlign: "left" }}>
    required
  </td>

  <td style={{ textAlign: "left" }}>
    Event name, which will also serve as the KPI in your reporting. **[Learn more](/docs/glossary#kpi)**
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    label
  </td>

  <td style={{ textAlign: "left" }}>
    string
  </td>

  <td style={{ textAlign: "left" }}>
    optional
  </td>

  <td style={{ textAlign: "left" }}>
    Additional description of your event.
  </td>
</tr>

<tr>
  <td style={{ textAlign: "left" }}>
    value
  </td>

  <td style={{ textAlign: "left" }}>
    integer
  </td>

  <td style={{ textAlign: "left" }}>
    optional
  </td>

  <td style={{ textAlign: "left" }}>
    Can be used to evaluate visitor interactions with individual site objects or content items.

    * \*NOTE:\*\* this value must be non-negative and not a float
  </td>
</tr>
```

| Key/Property |
| ------------ |
| type         |

\\

## Cache management

The purpose of cache management is to address the following issues:

* **Re-allocation in bucketing mode :**

In bucketing mode, the SDK ensures that a visitor remains in the variation where they were initially allocated, even if the customer or dynamic allocation changes the traffic allocation. This is because in bucketing mode, the assignment is made on the local device, so changing campaign allocation on the platform could cause visitors to see different campaigns.

* **Handle offline mode on client side :**

When the cache is enabled, the SDK attempts to retrieve the latest visitor data (campaign assignments) from the cache. It also saves all failed hits and visitor exposures to resend them later.

By default, the Flagship JS SDK provides a default cache manager implementation on the client side. However, you can use your own cache manager by implementing the `IVisitorCacheImplementation` and `IHitCacheImplementation` interfaces through the visitorCacheImplementation and hitCacheImplementation properties of the [configuration](#advanced-configuration).

### Visitor Cache

The visitor cache is used to store the visitor data in a database through the `IVisitorCacheImplementation` interface which defines the methods that an object must implement to manager it.

```typescript
interface IVisitorCacheImplementation {
    cacheVisitor(visitorId: string, data: VisitorCacheDTO):Promise<void>
    lookupVisitor(visitorId: string): Promise<VisitorCacheDTO>
    flushVisitor(visitorId: string): Promise<void>
}
```

#### `cacheVisitor` method

This method is invoked when the SDK needs to store visitor information in your database.

* **`public cacheVisitor(visitorId: string, data: object):Promise<void>`**

It accepts 2 arguments :

| Argument  | Type   | Description                                                                                              |
| --------- | ------ | -------------------------------------------------------------------------------------------------------- |
| visitorId | string | The ID of the visitor                                                                                    |
| Data      | object | The visitor data. The object adheres to the structure of the [`VisitorCacheDTO`](#visitorcachedto) type. |

#### `lookupVisitor` method

This method is invoked when the SDK needs to retrieve visitor information associated with a specific visitor ID from your database.

It should return an object of type `VisitorCacheDTO` that adheres to this structure [see](#visitorcachedto).

* **`public lookupVisitor(visitorId: string): Promise<object>`**

It accepts one argument :

| Argument  | Type   | Description |
| --------- | ------ | ----------- |
| visitorId | string | visitor ID  |

#### `flushVisitor` method

This method is invoked when the SDK needs to delete the visitor information associated with a specific visitor ID from your database.

* **`public flushVisitor(visitorId: string): Promise<void>`**

It accepts one argument :

| Argument  | Type   | Description           |
| --------- | ------ | --------------------- |
| visitorId | string | The ID of the visitor |

> 📘 Information
>
> * This method is called every time the [`setConsent`](#setconsent-function) method or the [hasConsented](https://docs.abtasty.com/server-side/sdks/react/archived-versions/archived-react-v4/archived-react-v4-js-reference) key of the props [visitorData](#visitordata) is set to `false`.

#### VisitorCacheDTO

```typescript
type VisitorCacheDTO = {
  version: number;
  data: {
    visitorId: string;
    anonymousId: string | null;
    consent?: boolean;
    context?: Record<string, boolean|number|string>;
    assignmentsHistory?: Record<string, string>;
    campaigns?: Array<{
      campaignId: string;
      variationGroupId: string;
      variationId: string;
      isReference?: boolean;
      type: string;
      activated?: boolean;
      flags?: Record<string, unknown>;
    }>;
  };
};
```

### Hit Cache

The hit cache is used to store hits in your database based on the strategy used through the `IHitCacheImplementation` interface which defines the methods that an object must implement to handle it.

```typescript
interface IHitCacheImplementation {
    cacheHit(hits: Record<string, HitCacheDTO>):Promise<void>
    lookupHits():Promise<Record<string, HitCacheDTO>>
    flushHits(hitKeys: string[]): Promise<void>
    flushAllHits(): Promise<void>
}
```

#### `cacheHit` method

This method is invoked to store hits based on cache the strategy used.

* **`public cacheHit(hits: Record<string, HitCacheDTO>):Promise<void>`**

It accepts 1 argument :

```
  <th style={{ textAlign: "left" }}>
    Type
  </th>

  <th style={{ textAlign: "left" }}>
    Description
  </th>
</tr>
```

```
  <td style={{ textAlign: "left" }}>
    object
  </td>

  <td style={{ textAlign: "left" }}>
    This is a key/value object where:

    * key  is a unique ID for each hit
    * value is an object that follows the shape of type [`HitCacheDTO`](#hitCachedto).
  </td>
</tr>
```

| Argument |
| -------- |
| hits     |

#### `lookupHits` method

This method is invoked to load all hits from your database and attempt to send them in the background.

It should return an object where the key is a unique ID for each hit, and the value is an object of type `HitCacheDTO` that adheres to this structure [see](#hitCachedto).

* **`public lookupHits():Promise<Record<string, HitCacheDTO>>`**

> 📘 Information
>
> * `Hits` older than 4H will be ignored during the re-sending process.

#### `flushHits` function

This method is invoked to delete all hits that match the unique hit IDs from your database.

**NOTE:** It is called every time [`setConsent`](#setconsent-function) is set to false, erasing all of the visitor's hits from the database.

* **`public flushHits(hitKeys: string[]): Promise<void>`**

It accepts one argument :

| Argument | Type      | Description       |
| -------- | --------- | ----------------- |
| hitKeys  | string\[] | Unique ID of hits |

> 📘 \* This method is called every time the [`setConsent`](#setconsent-function) method or the [hasConsented](https://docs.abtasty.com/server-side/sdks/react/archived-versions/archived-react-v4/archived-react-v4-js-reference) key of the props [visitorData](#visitordata) is set to `false`.

#### `flushAllHits` function

This method is invoked to delete all hits from your database without exception.

* **`public flushAllHits(): Promise<void>`**

#### HitCacheDTO

```typescript
type HitCacheLookupDTO = {
  version: number;
  data: {
    visitorId: string;
    anonymousId: string | null;
    type: HitType | "ACTIVATE";
    time: number;
    content?: Record<string, unknown>;
  };
};
```

#### `IHitCacheImplementation` implementation

**localStorage**

This is an implementation of the `IHitCacheImplementation` interface using `localStorage`.

```typescript
import { Flagship, CacheStrategy } from "@flagship.io/react-sdk";

const FS_HIT_PREFIX = 'FS_DEFAULT_HIT_CACHE'


const hitCacheImplementation = {
  cacheHit (hits) {
    const localDatabaseJson = localStorage.getItem(FS_HIT_PREFIX) || '{}'
    const localDatabase = JSON.parse(localDatabaseJson)

    const newLocalDatabase = {
      ...localDatabase,
      ...hits
    }

    localStorage.setItem(FS_HIT_PREFIX, JSON.stringify(newLocalDatabase))
    return Promise.resolve()
  },
  lookupHits () {
    const localDatabaseJson = localStorage.getItem(FS_HIT_PREFIX) || '{}'
    const localDatabase = JSON.parse(localDatabaseJson)
    return Promise.resolve(localDatabase)
  },
  flushHits (hitKeys) {
    const localDatabaseJson = localStorage.getItem(FS_HIT_PREFIX) || '{}'
    const localDatabase = JSON.parse(localDatabaseJson)

    hitKeys.forEach(key => {
      delete localDatabase[key]
    })

    localStorage.setItem(FS_HIT_PREFIX, JSON.stringify(localDatabase))
    return Promise.resolve()
  },
  flushAllHits () {
    localStorage.removeItem(FS_HIT_PREFIX)
    return Promise.resolve()
  }
}

Flagship.start(ENV_ID, API_KEY, {
  hitCacheImplementation: hitCacheImplementation,
  trackingManagerConfig: {
    batchIntervals: 5,
    poolMaxSize: 10,
    cacheStrategy: CacheStrategy.CONTINUOUS_CACHING
  }
})
```

**Redis**

This is an implementation of the `IHitCacheImplementation` interface using `redis`.

```javascript
import { Flagship, CacheStrategy } from "@flagship.io/react-sdk";
import Redis from 'ioredis'

function hitCacheImplementation (host, port, dbIndex) {
  const redis = new Redis({
    host,
    port
  })

  redis.select(dbIndex)

  return {

    async cacheHit (hits) {
      const multi = redis.multi()
      Object.entries(hits).forEach(([key, value]) => {
        multi.set(key, JSON.stringify(value))
      })
      await multi.exec()
    },
    async lookupHits () {
      const hits:Record<string, HitCacheDTO> = {}
      const keys = await redis.keys('*')
      if (!keys.length) {
        return hits
      }
      const redisData = await redis.mget(keys)

      redisData.forEach((value, index) => {
        if (!value) {
          return
        }
        hits[keys[index]] = JSON.parse(value)
      })
      return hits
    },
    async flushHits (hitKeys) {
      await redis.del(hitKeys)
    },

    async flushAllHits () {
      const keys = await redis.keys('*')
      if (!keys.length) {
        return
      }
      await redis.del(keys)
    }
  }
}

Flagship.start(ENV_ID, API_KEY, {
  hitCacheImplementation:hitCacheImplementation('127.0.0.1', '6379', 2),
  trackingManagerConfig: {
    batchIntervals: 10,
    poolMaxSize: 100,
    cacheStrategy: CacheStrategy.PERIODIC_CACHING
  }
})
```

In the LocalStorage implementation, the `localStorage` web API is used to store, retrieve, and delete hits. In the Redis implementation, the `ioredis` library is used to interact with a Redis database for the same purposes. Both implementations are passed to the `Flagship.start` method as part of the configuration object.

## Predefined visitor context keys

The Flagship SDK contains predefined visitor context keys.

The keys marked as **Yes** in the **Auto-set by SDK** column will be automatically set, while the ones marked as **No** need to be set by customer.

All possible predefined keys are listed below:

| SDK constant Name    | Description                                            | Context variable name   | Type       | Auto-set by SDK | Example         |
| -------------------- | ------------------------------------------------------ | ----------------------- | ---------- | --------------- | --------------- |
| DEVICE\_LOCALE       | Language of the device                                 | sdk\_deviceLanguage     | String     | No              | fra             |
| DEVICE\_TYPE         | Type of the device                                     | sdk\_deviceType         | DeviceType | No              | Mobile          |
| DEVICE\_MODEL        | Model of the device                                    | sdk\_deviceModel        | String     | No              | samsung E1200   |
| LOCATION\_CITY       | City geolocation                                       | sdk\_city               | String     | No              | toulouse        |
| LOCATION\_REGION     | Region geolocation                                     | sdk\_region             | String     | No              | occitanie       |
| LOCATION\_COUNTRY    | Country geolocation                                    | sdk\_country            | String     | No              | France          |
| LOCATION\_LAT        | Current Latitude                                       | sdk\_lat                | Double     | No              | 43.623647       |
| LOCATION\_LONG       | Current Longitude                                      | sdk\_long               | Double     | No              | 1.445397        |
| OS\_NAME             | Name of the OS                                         | sdk\_osName             | String     | No              | ubuntu / centos |
| OS\_VERSION\_NAME    | Version name of the OS                                 | sdk\_osVersionName      | String     | No              | 9.0.0           |
| OS\_VERSION\_CODE    | Version code of the OS                                 | sdk\_osVersionCode      | Number     | No              | 24              |
| CARRIER\_NAME        | Name of the carrier or mobile virtual network operator | sdk\_carrierName        | String     | No              | free            |
| INTERNET\_CONNECTION | What is the internet connection                        | sdk\_internetConnection | String     | No              | 5g              |
| APP\_VERSION\_NAME   | Version name of the app                                | sdk\_versionName        | String     | No              | 1.1.2-beta      |
| APP\_VERSION\_CODE   | Version code of the app                                | sdk\_versionCode        | Number     | No              | 40              |
| INTERFACE\_NAME      | Name of the interface                                  | sdk\_interfaceName      | String     | No              | ProductPage     |
| FLAGSHIP\_CLIENT     | Flagship SDK client (Reserved)                         | fs\_client              | String     | Yes             | TS              |
| FLAGSHIP\_VERSION    | Version of the Flagship SDK (Reserved)                 | fs\_version             | String     | Yes             | 4.0.0           |
| FLAGSHIP\_VISITOR    | Current visitor id (Reserved)                          | fs\_users               | String     | Yes             | visitor\_id     |
