> For the complete documentation index, see [llms.txt](https://docs.caf.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.caf.io/caf-sdk/caf-sdk-pt-br/react-native/standalone-modules/cafsmartauth/native-modules/import-native-module.md).

# Importar módulos nativos

## Como Usar o Módulo Nativo CafSmartAuth no React Native

Este guia detalhado explica como integrar o `CafSmartAuth` módulo nativo no seu projeto React Native usando TypeScript. Ele inclui a criação de um módulo e de um hook personalizado para gerenciar eventos e métodos fornecidos pelo SDK nativo.

### 1. Crie o `module.ts` Arquivo

Este arquivo importa o módulo nativo e configura um `NativeEventEmitter` para lidar com os eventos emitidos pelo módulo.

#### Exemplo de implementação

```ts
import { NativeModules, NativeEventEmitter, Platform } from 'react-native';

const IS_ANDROID = Platform.OS === 'android';

const module = NativeModules.CafSmartAuthBridgeModule;

const moduleEventEmitter = IS_ANDROID
  ? new NativeEventEmitter()
  : new NativeEventEmitter(module);

export { module, moduleEventEmitter };
```

### 2. Crie o `useSmartAuth.ts` Hook

Este hook gerencia os eventos e o estado associados ao `CafSmartAuth` módulo. Ele usa o `moduleEventEmitter` para ouvir os eventos emitidos pelo módulo nativo.

#### Funções Principais

* **`formattedOptions`**: Formata as configurações enviadas ao módulo nativo em formato JSON.
* **`useSmartAuth`**: Hook que:
  * Escuta os eventos emitidos pelo módulo nativo.
  * Atualiza o estado do React com base nos eventos.
* **`startSmartAuth`**: Método para iniciar a autenticação usando o módulo nativo.
* **`requestLocationPermissions`**: Método para solicitar permissões de localização ao usuário.

#### Exemplo de implementação

```ts
import { useState, useEffect } from 'react';

import { module, moduleEventEmitter } from '../modules/CafSmartAuth';

import {
  CafSmartAuthSettings,
  CafSmartAuthResponse,
  CafSmartAuthSuccess,
  CafSmartAuthPending,
} from '../hooks/types';

let responseFormattedOptions: string = '';

const formattedOptions = (settings: CafSmartAuthSettings): string => {
  const formatToJSON = JSON.stringify({
    ...settings,
  });

  return formatToJSON;
};

const useSmartAuth = (settings?: CafSmartAuthSettings) => {
  const [response, setResponse] = useState<CafSmartAuthResponse>({
    success: {
      isAuthorized: false,
      attemptId: null,
      attestation: null,
    },
    error: null,
    cancelled: false,
    isLoading: false,
    pending: {
      isAuthorized: false,
      attestation: null,
    },
  });

  responseFormattedOptions = formattedOptions(settings!);

  useEffect(() => {
    moduleEventEmitter.addListener(
      'CafSmartAuth_Success',
      (event: CafSmartAuthSuccess) => {
        setResponse({
          success: {
            isAuthorized: event.isAuthorized,
            attemptId: event.attemptId,
            attestation: event.attestation,
          },
          error: null,
          cancelled: false,
          isLoading: false,
          pending: {
            isAuthorized: false,
            attestation: null,
          },
        });
      },
    );

    moduleEventEmitter.addListener('CafSmartAuth_Error', (event: string) => {
      setResponse({
        success: {
          isAuthorized: false,
          attemptId: null,
          attestation: null,
        },
        error: event,
        cancelled: false,
        isLoading: false,
        pending: {
          isAuthorized: false,
          attestation: null,
        },
      });
    });

    moduleEventEmitter.addListener('CafSmartAuth_Cancel', (event: boolean) => {
      setResponse({
        success: {
          isAuthorized: false,
          attemptId: null,
          attestation: null,
        },
        error: null,
        cancelled: event,
        isLoading: false,
        pending: {
          isAuthorized: false,
          attestation: null,
        },
      });
    });

    moduleEventEmitter.addListener(
      'CafSmartAuth_Pending',
      (event: CafSmartAuthPending) => {
        setResponse({
          success: {
            isAuthorized: false,
            attemptId: null,
            attestation: null,
          },
          error: null,
          cancelled: false,
          isLoading: false,
          pending: {
            isAuthorized: event.isAuthorized,
            attestation: event.attestation,
          },
        });
      },
    );

    moduleEventEmitter.addListener('CafSmartAuth_Loading', (event: boolean) => {
      setResponse({
        success: {
          isAuthorized: false,
          attemptId: null,
          attestation: null,
        },
        error: null,
        cancelled: false,
        isLoading: event,
        pending: {
          isAuthorized: false,
          attestation: null,
        },
      });
    });

    moduleEventEmitter.addListener('CafSmartAuth_Loaded', (event: boolean) => {
      setResponse({
        success: {
          isAuthorized: false,
          attemptId: null,
          attestation: null,
        },
        error: null,
        cancelled: false,
        isLoading: event,
        pending: {
          isAuthorized: false,
          attestation: null,
        },
      });
    });

    return () => {
      moduleEventEmitter.removeAllListeners('CafSmartAuth_Success');
      moduleEventEmitter.removeAllListeners('CafSmartAuth_Pending');
      moduleEventEmitter.removeAllListeners('CafSmartAuth_Error');
      moduleEventEmitter.removeAllListeners('CafSmartAuth_Cancel');
      moduleEventEmitter.removeAllListeners('CafSmartAuth_Loading');
      moduleEventEmitter.removeAllListeners('CafSmartAuth_Loaded');
    };
  }, []);

  return {
    success: response.success,
    error: response.error,
    cancelled: response.cancelled,
    pending: response.pending,
    isLoading: response.isLoading,
  };
};

const startSmartAuth = (
  mfaToken: string,
  faceAuthToken: string,
  policyId: string,
  personId: string,
) => {
  module.startSmartAuth(
    mfaToken,
    faceAuthToken,
    personId,
    policyId,
    responseFormattedOptions,
  );
};

const requestLocationPermissions = async () => {
  await module.requestLocationPermissions();
};

export { startSmartAuth, requestLocationPermissions, useSmartAuth };
```

### 3. Métodos Disponíveis

* **`useSmartAuth`**: Um hook que fornece os seguintes estados:
  * `sucesso`: Informações sobre autenticações bem-sucedidas.
  * `error`: Detalhes sobre os erros ocorridos.
  * `cancelado`: Indica se a operação foi cancelada.
  * `pendente`: Informações sobre autenticações pendentes.
  * `isLoading`: Indica se a autenticação está em andamento.
* **`startSmartAuth`**: Método para iniciar o processo de autenticação.
  * **Parâmetros**:
    * `mfaToken`: Token de autenticação multifator.
    * `faceAuthToken`: Token para autenticação facial.
    * `policyId`: ID da política de autenticação.
    * `personId`: ID da pessoa a ser autenticada.
* **`requestLocationPermissions`**: Método para solicitar permissões de localização ao usuário (somente Android).

### 4. Integração do Projeto

Veja como implementar o hook em seu projeto, siga [Código-fonte](https://docs.caf.io/caf-sdk/caf-sdk-pt-br/react-native/standalone-modules/cafsmartauth/native-modules/source-code.md)


---

# 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://docs.caf.io/caf-sdk/caf-sdk-pt-br/react-native/standalone-modules/cafsmartauth/native-modules/import-native-module.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.
