> 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/expo-modules/import-expo-module.md).

# Importar módulos do Expo

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

Este guia detalhado explica como integrar o `CafSmartAuth` módulo do Expo ao seu projeto Expo 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 `CafSmartAuthBridgeModule.ts` Arquivo

Este arquivo importa o módulo do Expo.

#### Exemplo de implementação

```ts
import { NativeModule, requireNativeModule } from "expo";

import { CafSmartAuthBridgeModuleEvents } from "./CafSmartAuthBridgeModule.types";

declare class CafSmartAuthBridgeModule extends NativeModule<CafSmartAuthBridgeModuleEvents> {
  startSmartAuth(
    mfaToken: string,
    faceAuthToken: string,
    personId: string,
    policyId: string,
    jsonString: string
  ): Promise<void>;
  requestLocationPermissions(): Promise<void>;
}

// Esta chamada carrega o objeto do módulo nativo a partir do JSI.
export default requireNativeModule<CafSmartAuthBridgeModule>(
  "CafSmartAuthBridgeModule"
);
```

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

Este hook gerencia os eventos e o estado associados ao `CafSmartAuth` módulo.

#### 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 CafSmartAuthBridgeModule, {
  CafSmartAuthSettings,
  CafSmartAuthResponse,
  CafSmartAuthSuccess,
  CafSmartAuthError,
  CafSmartAuthPending,
  CafSmartAuthCancel,
  CafSmartAuthLoading,
  CafSmartAuthLoaded,
} from "../";

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(() => {
    CafSmartAuthBridgeModule.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,
          },
        });
      }
    );

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

    CafSmartAuthBridgeModule.addListener(
      "CafSmartAuth_Cancel",
      (event: CafSmartAuthCancel) => {
        setResponse({
          success: {
            isAuthorized: false,
            attemptId: null,
            attestation: null,
          },
          error: null,
          cancelled: event.isCancelled,
          isLoading: false,
          pending: {
            isAuthorized: false,
            attestation: null,
          },
        });
      }
    );

    CafSmartAuthBridgeModule.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,
          },
        });
      }
    );

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

    CafSmartAuthBridgeModule.addListener(
      "CafSmartAuth_Loaded",
      (event: CafSmartAuthLoaded) => {
        setResponse({
          success: {
            isAuthorized: false,
            attemptId: null,
            attestation: null,
          },
          error: null,
          cancelled: false,
          isLoading: event.isLoaded,
          pending: {
            isAuthorized: false,
            attestation: null,
          },
        });
      }
    );

    return () => {
      CafSmartAuthBridgeModule.removeAllListeners("CafSmartAuth_Success");
      CafSmartAuthBridgeModule.removeAllListeners("CafSmartAuth_Pending");
      CafSmartAuthBridgeModule.removeAllListeners("CafSmartAuth_Error");
      CafSmartAuthBridgeModule.removeAllListeners("CafSmartAuth_Cancel");
      CafSmartAuthBridgeModule.removeAllListeners("CafSmartAuth_Loading");
      CafSmartAuthBridgeModule.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
) => {
  CafSmartAuthBridgeModule.startSmartAuth(
    mfaToken,
    faceAuthToken,
    personId,
    policyId,
    responseFormattedOptions
  );
};

const requestLocationPermissions = async () => {
  await CafSmartAuthBridgeModule.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](/caf-sdk/caf-sdk-pt-br/react-native/standalone-modules/cafsmartauth/expo-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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.caf.io/caf-sdk/caf-sdk-pt-br/react-native/standalone-modules/cafsmartauth/expo-modules/import-expo-module.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
