1import * as Linking from 'expo-linking';
2import * as WebBrowser from 'expo-web-browser';
3import React from 'react';
4import { StyleSheet } from 'react-native';
5
6import Button from '../../components/Button';
7import Configurator, { ConfiguratorChoiceType } from '../../components/Configurator';
8import HeadingText from '../../components/HeadingText';
9import MonoText from '../../components/MonoText';
10
11const openAuthSessionConfigurationChoices: ConfiguratorChoiceType[] = [
12  {
13    name: 'shouldPrompt',
14    title: 'Should prompt',
15    initial: false,
16  },
17  {
18    name: 'createTask',
19    title: 'Create task',
20    initial: true,
21  },
22];
23
24export default function OpenAuthSessionAsyncDemo() {
25  const [options, setOptions] = React.useState<{ shouldPrompt?: boolean; createTask?: boolean }>(
26    {}
27  );
28  const [authResult, setAuthResult] = React.useState<WebBrowser.WebBrowserAuthSessionResult | null>(
29    null
30  );
31
32  const openAuthSession = React.useCallback(async () => {
33    const redirectUrl = Linking.makeUrl('redirect');
34    const result = await WebBrowser.openAuthSessionAsync(
35      `https://fake-auth.netlify.com?state=faker&redirect_uri=${encodeURIComponent(
36        redirectUrl
37      )}&prompt=${options.shouldPrompt ? 'consent' : 'none'}`,
38      redirectUrl,
39      { createTask: options.createTask }
40    );
41
42    setAuthResult(result);
43  }, [options]);
44
45  return (
46    <>
47      <HeadingText>openAuthSessionAsync</HeadingText>
48      <Configurator choices={openAuthSessionConfigurationChoices} onChange={setOptions} />
49      <Button style={styles.button} onPress={openAuthSession} title="Open web auth session" />
50      {authResult && <MonoText>result: {JSON.stringify(authResult, null, 2)}</MonoText>}
51    </>
52  );
53}
54
55const styles = StyleSheet.create({
56  button: {
57    marginVertical: 10,
58    alignItems: 'flex-start',
59  },
60});
61