> For the complete documentation index, see [llms.txt](https://user.netmera.com/netmera-developer-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://user.netmera.com/netmera-developer-guide/platforms/react-native/remote-config.md). Agents can also search and read this documentation through its [MCP server](https://user.netmera.com/netmera-developer-guide/~gitbook/mcp).

# Remote Config

Remote Config lets you change your app's behavior and appearance without releasing a new version. You define variables on the Netmera panel, the SDK delivers the values resolved for the current user, and your app reads them with typed getters.

{% hint style="info" %}
Remote Config requires `react-native-netmera` **2.5.0** or later. This version bundles Netmera Android SDK 4.28.0 and iOS SDK 4.31.0, so no extra native setup is needed.
{% endhint %}

Everything below is exported from the package root:

```typescript
import {
  Netmera,
  NetmeraRemoteConfig,
  isRemoteConfigFetchError,
  REMOTE_CONFIG_FETCH_ERROR_CODE,
} from 'react-native-netmera';
```

## How It Works

* The SDK keeps the last fetched config in a local cache. The config is available right after app start, offline, and across restarts.
* The SDK does not poll. It refreshes the cache on its own when:
  1. the session start response reports a config version other than the cached one,
  2. a remote config silent push announces a new version,
  3. the identified user changes (values are resolved per user).
* `Netmera.getRemoteConfig()` reads the cache and never waits on the network.
* When the SDK refreshes the cache to a new version, it calls the listeners you added with `Netmera.addRemoteConfigUpdateListener()`.
* Every config has an app-wide `version`. An app without any variables has version `0`, and the SDK never fetches it.

## Reading the Config

`Netmera.getRemoteConfig()` returns `Promise<NetmeraRemoteConfig | null>` with a snapshot of the cached config. The result can be `null`, and every getter returns `null` for a missing key, so keep a default for every value.

```typescript
const config = await Netmera.getRemoteConfig();

const ctaLabel = config?.getString('cta_label') ?? 'Buy now';
const relatedLimit = config?.getInteger('related_limit') ?? 10;
const showReviews = config?.getBoolean('show_reviews') ?? false;
```

`getRemoteConfig()` resolves `null` when:

* nothing has been fetched yet, for example on the first app start before the first fetch completes,
* the app has no remote config variables,
* the SDK is not operating: it is not initialized, it is paused, or it was stopped with `Netmera.kill()`,
* the identified user has just changed and the new user's config has not arrived yet.

{% hint style="info" %}
Read the config once per screen or flow and keep the snapshot. Each call crosses the native bridge and parses the config, so don't call `getRemoteConfig()` from hot paths such as `renderItem` or on every render.
{% endhint %}

## Reading Values

All getters are strict. A getter returns `null` when the key is missing, when it holds JSON `null`, or when it holds another type. Nothing is converted: a variable authored as the string `"42"` is not returned by `getNumber`, and the number `42` is not returned by `getString`.

| Method            | Returns (or `null`)                 | Returns a value when the variable is                                               |
| ----------------- | ----------------------------------- | ---------------------------------------------------------------------------------- |
| `getString(key)`  | `string`                            | a string                                                                           |
| `getBoolean(key)` | `boolean`                           | a boolean                                                                          |
| `getNumber(key)`  | `number`                            | any number (`42`, `2.5`)                                                           |
| `getInteger(key)` | `number`                            | a whole number JavaScript holds exactly (`42` and `42.0` yes, `2.5` and `1e20` no) |
| `getObject(key)`  | `Readonly<Record<string, unknown>>` | a JSON object, returned as a plain object                                          |
| `getArray(key)`   | `ReadonlyArray<unknown>`            | a JSON array                                                                       |
| `getValue(key)`   | `unknown`                           | any type, untyped                                                                  |

Other `NetmeraRemoteConfig` members:

| Member          | Description                                                                                                |
| --------------- | ---------------------------------------------------------------------------------------------------------- |
| `version`       | Config version from Netmera.                                                                               |
| `has(key)`      | `true` when the key exists, JSON `null` included. Tells a missing key apart from a `null` or mistyped one. |
| `keys()`        | All keys, in alphabetical order.                                                                           |
| `getAll()`      | Every variable as a read-only object, with the JSON types authored on the panel.                           |
| `isEmpty()`     | `true` when the config has no variables.                                                                   |
| `equals(other)` | `true` when both configs have the same version and the same variables.                                     |
| `toString()`    | The version and the keys, without the values, so logging a config does not expose them.                    |

`JSON.stringify(config)` returns all variables as JSON text, for example to pass them to a WebView.

### Missing or Mistyped Variables

When a getter returns `null`, use `has()` to find out why:

```typescript
const limit = config.getInteger('related_limit');

if (limit === null) {
  if (config.has('related_limit')) {
    console.warn('related_limit is JSON null or not a whole number');
  } else {
    console.warn('related_limit is not defined on the panel');
  }
}
```

### Nested Objects and Arrays

Consider a `paywall` variable authored as a JSON object:

```json
{
  "title": "Go Premium",
  "discount": 0.2,
  "plans": ["monthly", "yearly"]
}
```

`getObject()` returns it as a plain object. Its fields are `unknown`, so check their types before you use them:

```typescript
const paywall = config?.getObject('paywall');

const title = paywall?.title;
const discount = paywall?.discount;
const plans = paywall?.plans;

const paywallTitle = typeof title === 'string' ? title : 'Upgrade';
const paywallDiscount = typeof discount === 'number' ? discount : 0;
const paywallPlans = Array.isArray(plans)
  ? plans.filter((plan): plan is string => typeof plan === 'string')
  : [];
```

Arrays work the same way:

```typescript
const tags = (config?.getArray('tags') ?? []).filter(
  (tag): tag is string => typeof tag === 'string'
);
```

{% hint style="info" %}
Objects and arrays from a config are deeply frozen, so one part of the app cannot change a snapshot that another part keeps reading. Copy them before you modify them, for example `[...tags]` or `{ ...paywall }`.
{% endhint %}

## Listening for Updates

`Netmera.addRemoteConfigUpdateListener(handler)` calls `handler` with the new `NetmeraRemoteConfig` whenever the SDK refreshes the config to a new version on its own. This includes the first fetch on a fresh install and the fetch after the identified user changes. It returns a subscription; call `remove()` on it to stop listening.

Updates that arrive before you subscribe are not replayed. Subscribe first, then read the cache once, so an update in between is not missed.

The following hook keeps a component in sync with the latest config:

```typescript
import { useEffect, useState } from 'react';
import { Netmera, NetmeraRemoteConfig } from 'react-native-netmera';

export function useRemoteConfig(): NetmeraRemoteConfig | null {
  const [config, setConfig] = useState<NetmeraRemoteConfig | null>(null);

  useEffect(() => {
    let active = true;

    // Subscribe first, then read the cache, so an update in between is not missed.
    const subscription = Netmera.addRemoteConfigUpdateListener(setConfig);
    Netmera.getRemoteConfig().then((cached) => {
      // An update that arrived meanwhile is newer than this cache read: keep it.
      if (active) {
        setConfig((current) => current ?? cached);
      }
    });

    return () => {
      active = false;
      subscription.remove();
    };
  }, []);

  return config;
}
```

```typescript
function ProductScreen() {
  const config = useRemoteConfig();

  const ctaLabel = config?.getString('cta_label') ?? 'Buy now';
  const showReviews = config?.getBoolean('show_reviews') ?? false;
  // ...
}
```

{% hint style="info" %}

* You can add as many listeners as you need; each subscription is independent.
* Results of `Netmera.fetchRemoteConfig()` go only to that call's caller, never to the update listeners. If one screen fetches, pass the result on yourself, or other screens keep the config they have until the next refresh by the SDK.
* After `Netmera.kill()`, no updates arrive until the app restarts.
  {% endhint %}

## Fetching on Demand

`Netmera.fetchRemoteConfig()` returns `Promise<NetmeraRemoteConfig>` and fetches the config from Netmera regardless of the cache, for example for pull-to-refresh. A successful fetch also updates the cache that `getRemoteConfig()` reads.

Use it only when you need the latest values immediately. The SDK already keeps the cache up to date.

```tsx
import { useState } from 'react';
import { RefreshControl, ScrollView } from 'react-native';
import {
  Netmera,
  NetmeraRemoteConfig,
  isRemoteConfigFetchError,
} from 'react-native-netmera';

function SettingsScreen() {
  const [config, setConfig] = useState<NetmeraRemoteConfig | null>(null);
  const [refreshing, setRefreshing] = useState(false);

  const onRefresh = async () => {
    setRefreshing(true);
    try {
      setConfig(await Netmera.fetchRemoteConfig());
    } catch (error) {
      // The cache is unchanged: keep showing the config you have.
      if (isRemoteConfigFetchError(error)) {
        console.warn(`Remote config fetch failed: ${error.userInfo.reason}`);
      }
    } finally {
      setRefreshing(false);
    }
  };

  return (
    <ScrollView
      refreshControl={
        <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
      }
    >
      {/* ... */}
    </ScrollView>
  );
}
```

### Handling Errors

A failed fetch leaves the cache unchanged. The promise rejects with an `Error` whose `code` is `'2037'` (`REMOTE_CONFIG_FETCH_ERROR_CODE`) and whose `userInfo.reason` tells what went wrong. `isRemoteConfigFetchError(error)` narrows a caught error to this shape.

| `userInfo.reason` | Meaning                                                                                                                |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `request`         | The request failed, for example because there is no connection, it timed out, or the server returned an error.         |
| `invalidResponse` | The response had no usable config.                                                                                     |
| `cancelled`       | The fetch was dropped while in flight because the identified user changed, the API key changed, or the SDK was killed. |
| `notOperating`    | The SDK is not initialized, is paused, or was killed. Nothing was sent.                                                |

```typescript
try {
  const config = await Netmera.fetchRemoteConfig();
  // use config
} catch (error) {
  if (isRemoteConfigFetchError(error) && error.userInfo.reason === 'request') {
    // Offline or server error: keep serving the cached config.
  }
}
```

{% hint style="info" %}
If the identified user changes while a fetch is in flight, Android resolves with the config cached by then when there is one, and iOS always rejects with `cancelled`.
{% endhint %}

## Behavior Notes

* **User change:** When `Netmera.identifyUser()` switches to another user, the SDK drops the previous user's config and fetches the new one. `getRemoteConfig()` resolves `null` until it arrives, and the update listeners are called when it does.
* **Kill:** `Netmera.kill()` clears the cached config. Afterwards `getRemoteConfig()` resolves `null`, `fetchRemoteConfig()` rejects with `notOperating`, and no updates arrive until the app restarts.
* **Large integers:** Integers above `Number.MAX_SAFE_INTEGER` (2^53 - 1) lose precision in JavaScript, and `getInteger()` returns `null` for them. Author large IDs as strings.
* **Same result on both platforms:** The config crosses the native bridge as JSON text, so JSON `null` values and number types read the same on Android and iOS.

## Best Practices

* Ship a default for every value.
* Read the config once per screen or flow and keep the snapshot, so values don't change in the middle of an interaction.
* Use the update listener instead of calling `fetchRemoteConfig()` periodically.
* Use `has()` to tell a missing variable apart from a `null` or mistyped one, for example for logging.
* Log configs with `toString()`, not `JSON.stringify()`, if your variables can hold values you don't want in logs.

## Example App

The [Netmera React Native TypeScript example app](https://github.com/Netmera/Netmera-React-Native-Typescript-Example/blob/main/src/screens/RemoteConfig.tsx) has a Remote Config screen that reads the cache, forces a fetch, reads a value with each getter, and shows update listener calls.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://user.netmera.com/netmera-developer-guide/platforms/react-native/remote-config.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
