So my logic is for authentication I need to create a component where all functions and sensitive details is kept then I should use hooks to call those functions in the login form, grab the access tokens etc. Please correct me if this is not the correct approach. However I cannot make this work as functions are undefined when I run the app.
ERROR: setEmail, setPassword, signInWithEmail, signUpWithEmail are not defined.
App.js
import { StyleSheet, View } from 'react-native';
import { Button, Input } from 'react-native-elements';
import authService from './component/authService';
export default function App() {
return (
<View style={styles.container}>
<View style={styles.container}>
<View style={[styles.verticallySpaced, styles.mt20]}>
<Input
label="Email"
leftIcon={{ type: 'font-awesome', name: 'envelope' }}
onChangeText={(text) => authService.setEmail(text)}
value={email}
placeholder="[email protected]"
autoCapitalize={'none'}
/>
</View>
<View style={styles.verticallySpaced}>
<Input
label="Password"
leftIcon={{ type: 'font-awesome', name: 'lock' }}
onChangeText={(text) => authService.setPassword(text)}
value={password}
secureTextEntry={true}
placeholder="Password"
autoCapitalize={'none'}
/>
</View>
<View style={[styles.verticallySpaced, styles.mt20]}>
<Button title="Sign in" disabled={loading} onPress={() => signInWithEmail()} />
</View>
<View style={styles.verticallySpaced}>
<Button title="Sign up" disabled={loading} onPress={() => signUpWithEmail()} />
</View>
</View>
</View>
);
}
authService.tsx
import React, { useState } from "react";
import { supabase } from '../lib/supabase';
import { Alert } from 'react-native';
export default function AuthService() {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [loading, setLoading] = useState(false)
async function signInWithEmail() {
setLoading(true)
const { error } = await supabase.auth.signInWithPassword({
email: email,
password: password,
})
if (error) Alert.alert(error.message)
setLoading(false)
}
async function signUpWithEmail() {
setLoading(true)
const {
data: { session },
error,
} = await supabase.auth.signUp({
email: email,
password: password,
})
if (error) Alert.alert(error.message)
if (!session) Alert.alert('Please check your inbox for email verification!')
setLoading(false)
}
}
You can use
react-native-event-listenersfor trigging the function on an other component and also you can get value from that listener.The event listeners also work across different files. You only have to import the EventRegister in every file you need to send or receive your events.
Here is the example
You should have to import the lister by installing if from npm.
You can trigger function like this refreshTBD is a Key you can add any key here.
Here is the function that hit when we want to hit by emitting. refreshTBD is key. you can call this useEffect in your authService.tsx
For more detail you can visit react-native-event-listeners