Scaricare i file di React Native Integration da https://github.com/Crowdhandler/ch-react-native-integration/releases/download/1.0.0/ch-react-native-integration.zip e aggiungere la cartella ch-react-native-integration al progetto.

In questo esempio utilizzeremo CrowdHandler per proteggere alcuni prodotti in un'applicazione di e-commerce. La sala d'attesa si attiverà per i prodotti selezionati quando l'utente invocherà la navigazione.

1. Configurazione del provider CrowdHandler

Importare il CrowdHandlerProvider nel livello superiore dell'applicazione.

App.js

import { CrowdHandlerProvider } from './ch-react-native-integration';

Creare un oggetto all'interno dell'applicazione per gestire gli eventi.

Questi eventi sono chiamati da CrowdHandler per consentire di rispondere allo stato.

Sono necessari 2 ascoltatori di eventi.

onWait() - Richiamato quando CrowdHandler rileva che un utente deve essere inviato alla schermata della sala d'attesa.

onRedirect() - Richiamato quando CrowdHandler rileva che un utente deve essere inviato alla schermata che si sta proteggendo.

Opzionalmente, si possono usare altri due ascoltatori di eventi, onRequestStart() e onRequestEnd().

Questi vengono chiamati prima e dopo la richiesta di CrowdHandler e sono utili per mostrare all'utente che l'attività è in corso.

App.js

export default function App() {

    const CHEvents = {
        navigation: null, // holds the navigation stack so CrowdHandler can redirect the correct screens
        onWait: function (ch_response) { // required
            launchWaitingRoomScreen(ch_response); 
        },
        onRedirect: function (ch_response) { // required
            redirectToScreen(ch_response);
        },
        onRequestStart: function () {}, //optional
        onRequestEnd: function () {} // optional
    };
...

e creare funzioni per gestire gli eventi.

Qui si imposta il nome della schermata della sala d'attesa su "CHWaitingRoom".

Assicurarsi che questo nome sia uguale a quello della schermata nella pila di navigazione.

La ch_response restituita dalla funzione onWait contiene una proprietà chiamata referer. La usiamo per determinare se lo stack di navigazione deve sostituire la cronologia. Se il reindirizzamento proviene dalla sala d'attesa, non vogliamo che l'utente torni alla sala d'attesa quando clicca sul pulsante indietro.

App.js

const launchWaitingRoomScreen = (ch_response) => {
    ch_response.navigation.navigate('CHWaitingRoom', { ...ch_response.screen_config });
}
const redirectToScreen = (ch_response) => { 
    if(ch_response.referer === 'waiting_room') {
      ch_response.navigation.replace(ch_response.screen_config.redirect, ch_response.screen_config);
    } else {
      ch_response.navigation.navigate(ch_response.screen_config.redirect, ch_response.screen_config);
    }
}

Avvolgere la propria applicazione con il componente CrowdHandlerProvider, passando l'oggetto evento creato in precedenza, CHEvents e la propria chiave api pubblica come oggetti di scena. Opzionalmente, si può aggiungere un valore per `timeout` in millisecondi. Questo valore indica a CrowdHandler di reindirizzare alla schermata protetta in caso di timeout dell'API o di richiesta lenta. Se non viene impostato, il valore predefinito è 3000ms (o 3 secondi).

App.js

<CrowdHandlerProvider
    timeout={3000}
    chEvents={CHEvents}
    apiKey={"04b39378b6abc3d4ee870824371646a9d1e157b1a7720821add4c260108ebd48"}>
    <NavigationStack/>
</CrowdHandlerProvider>

2. Aggiungere la WebView CrowdHandler allo stack di navigazione.

Importate il componente CHWebView nel punto in cui state creando la pila di navigazione.

NavigationStack.js
import {CHWebView} from './ch-react-native-integration';

CHWebView è un componente che restituisce un componente WebView e richiede react-native-webview come dipendenza.

Per installare react-native-webview eseguire

aggiungere react-native-webview

o

npm install --save react-native-webview

Ulteriori informazioni su react-native-webview sono disponibili qui

https://github.com/react-native-webview/react-native-webview/blob/master/docs/Getting-Started.md

Nello stack di navigazione è necessaria una schermata per la sala d'attesa. Impostare la proprietà name con lo stesso valore impostato nella funzione `launchWaitingRoomScreen` di cui sopra; noi l'abbiamo impostata su CHWaitingRoom.

Importare il componente CHWebView e impostare il prop componente della schermata sul componente CHWebView.

This is the screen that the user will see if they are required to wait so its important that the name of the screen matches the name you specified in the method called by the onWait event in App.js.
i.e. <Stack.Screen name="CHWaitingRoom" component={CHWebView} />
NavigationStack.js
...
<Stack.Navigator> 
    <Stack.Screen name="Home" component={HomeScreen}/>
    <Stack.Screen name="Details" component={ProductsScreen}/>
    <Stack.Screen name="ProductScreen" component={ProductScreen} /> 
    <Stack.Screen name="CHWaitingRoom" component={CHWebView} />
</Stack.Navigator>
...

3. Intercettare i clic di navigazione

Per le pagine che si desidera proteggere, è necessario intercettare l'interazione di navigazione dell'utente e verificare con CrowdHandler prima di mostrare la schermata desiderata. Per farlo, importare il contesto `useCrowdHandler` dal file CrowdHandlerGatekeeper nel componente della schermata che gestisce l'input di navigazione.

ProductsScreen.js

import { useCrowdHandler } from "./ch-react-native-integration";

quindi portare il contesto CrowdHandler nel componente schermo.

ProductsScreen.js

export const ProductsScreen = ({ navigation }) => {

    const crowdhandler_gatekeeper = useCrowdHandler();

    // pass a reference of navigation to the gatekeeper
    // this allows CrowdHandler to redirect the user to the correct screen
    crowdhandler_gatekeeper.setNavigation(navigation);
...

Aggiungere una funzione per gestire quando un utente fa clic su un elemento di navigazione che lo porta a una schermata che si desidera proteggere.

È una buona idea controllare se la schermata a cui si sta navigando ha una proprietà slug o url.
Se non ce l'ha, non è necessario controllare con CrowdHandler.

ProductsScreen.js

export const ProductsScreen = ({ navigation }) => {
    const crowdhandler_gatekeeper = useCrowdHandler();

    // pass a reference of navigation to the gatekeeper
    // this allows CrowdHandler to redirect the user to the correct screen
    crowdhandler_gatekeeper.setNavigation(navigation);

    const handleCheckWithCrowdHandler = async (product) => {
        if (product.slug || product.url) {
            await crowdhandler_gatekeeper.redirectOrWait(product);
        } else {
            navigation.navigate(product.redirect, product)
        }
    }
...

e aggiungere questo gestore all'evento onPress del pulsante.

Crowdhandler può proteggere le schermate in base allo slug Sala d'attesa o in base all'url che si desidera proteggere.

ProductsScreen.js

// A collection of products
// Minimum requirements are that they have the waiting room slug or URL to protect
// and a screen to redirect to
// Analogous to params that are sent to react-navigator and any
// params that are set here are sent to the navigator on redirect

const products = [
    {
        slug: '0MAID6M2iMjNW1WZs', // waiting room slug from crowdhander admin
        redirect: 'ProductScreen', // the screen to redirect to
        title: 'Hiking Boots',
        productID: 'pct_000112312'
    }, {
        url: 'https://example.com/products/protected/page', // URL to protect -  set in crowdhander admin
        redirect: 'ProductScreen',
        // the screen to redirect to
        title: 'Head Torch',
        productID: 'pct_030112552' 
    }
]

{products.map((product) => {
    return (
        <Button
            key={product.productID}
            onPress = { () => {
                handleCheckWithCrowdHandler(product)} // send the data to check
            }
        >
        {product.title}
        </Button>
    )
})}
...

4. Mettere tutto insieme.

In questa implementazione, quando l'utente preme il pulsante, viene richiamato handleCheckWithCrowdHandler(), passando l'oggetto prodotto come argomento, ovvero

{
		slug: '0MAID6M2iMjNW1WZs', // waiting room slug from crowdhander admin
    	redirect: 'ProductScreen', // the screen to redirect to
    	title: 'Hiking Boots',
    	productID: 'pct_000112312'
    }
 

CrowdHandler esegue quindi un controllo in base alla proprietà slug o alla proprietà url dell'oggetto

Se l'utente deve attendere, viene richiamato l'evento onWait(), definito in App.js. Questo viene gestito dal gestore launchWaitingRoom(), anch'esso definito in App.js. Viene visualizzata la schermata CHWaitingRoom e viene caricata la sala d'attesa.

Se l'utente è in grado di accedere alla schermata protetta, viene richiamato onRedirect() e l'utente viene indirizzato alla schermata specificata nell'oggetto Prodotto, in questo caso SchermoProdotto.