Skip to content

Instantly share code, notes, and snippets.

@byronferguson
Created April 4, 2025 03:21
Show Gist options
  • Save byronferguson/60b820671b1bb73e84141f8bccfe7624 to your computer and use it in GitHub Desktop.
Save byronferguson/60b820671b1bb73e84141f8bccfe7624 to your computer and use it in GitHub Desktop.
React Native
import { api } from './index';
const PATH = '/v2/auth';
export function login(username: string, password: string) {
return api
.post(`${PATH}/login`, {
username,
password,
type: 'family',
})
.then(res => {
if (res.status !== 201) throw new Error('Login failed');
return res.data;
})
.catch(error => {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.error(`Error: ${error.response.status} - ${error.response.statusText}`);
// Throw a custom error based on the status code
if (error.response.status === 401) {
// throw new AuthenticationError('Unauthorized');
} else if (error.response.status === 500) {
// throw new ServerError('Internal Server Error');
}
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser
console.error('Network Error: Request failed to reach the server');
console.log('error.request :>> ', error.request);
// throw new NetworkError('Network Error');
} else {
// Something happened in setting up the request that triggered an Error
console.error('Error: ', error.message);
throw new Error('An unexpected error occurred');
}
});
}
import axios, { AxiosError } from 'axios';
export { AxiosError, AxiosInstance, AxiosResponse } from 'axios';
const _baseURL = 'https://api.mydomaon.com';
export const api = axios.create({
baseURL: _baseURL,
validateStatus: status => status >= 200 && status < 500,
headers: {
common: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
},
});
export function updateBaseUrl(baseURL = _baseURL): void {
api.defaults.baseURL = baseURL;
}
export function updateApiAuthToken(token: string): void {
api.defaults.headers.common.Authorization = `Bearer ${token}`;
}
export function removeApiAuthToken(): void {
api.defaults.headers.common.Authorization = undefined;
}
export function updateUtmCodeIdHeader(utmCodeId: string): void {
api.defaults.headers.common['utm-code-id'] = utmCodeId;
}
export function removeUtmCodeIdHeader(): void {
api.defaults.headers.common['utm-code-id'] = undefined;
}
export function isAxiosError<ResponseType>(error: unknown): error is AxiosError<ResponseType> {
return axios.isAxiosError(error);
}
import * as AuthService from '@/services/auth.service';
import Button from '@/components/ui/Button';
import { UiColors } from '@/constants/Colors';
import { storage } from '@/utilities/mmkv';
import { useMutation } from '@tanstack/react-query';
import { Redirect } from 'expo-router';
import { useState } from 'react';
import { StyleSheet, Text, TextInput, View } from 'react-native';
const signin = () => {
const [username, setUsername] = useState('[email protected]');
const [password, setPassword] = useState('password');
const [token, setToken] = useState(() => storage.getString('token'));
const login = useMutation({
mutationFn: ({ username, password }: any) => AuthService.login(username, password),
onSuccess(data) {
if (!data.token) return;
setToken(data.token);
console.log('data :>> ', data);
},
onError(error) {
console.log('Error:', error);
},
});
async function handleLogin() {
// Call the login service
console.log('Username:', username);
console.log('Password:', password);
await login.mutate({ username, password });
}
const session = null;
if (session) return <Redirect href="/" />;
return (
<View style={styles.container}>
<View style={{ gap: 12 }}>
<Text style={styles.headline}>SignIn</Text>
<Text>Username:</Text>
<TextInput
placeholder="Enter your username..."
style={styles.input}
value={username}
onChangeText={text => setUsername(text)}
/>
<Text>Password:</Text>
<TextInput
style={styles.input}
placeholder="Password"
value={password}
onChangeText={text => setPassword(text)}
secureTextEntry
/>
<Button label="login" onPress={handleLogin} style={{ alignSelf: 'stretch' }} />
{login.isPaused ? <Text>Attempting</Text> : null}
{login.isError ? <Text>Error: {login.error.message}</Text> : null}
{login.isSuccess ? <Text>Success</Text> : null}
<Text>Token: {token ?? ''}</Text>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
justifyContent: 'center',
backgroundColor: UiColors.background.white,
},
headline: {
textAlign: 'center',
marginTop: -100,
marginBottom: 50,
fontWeight: 700,
fontStyle: 'italic',
},
input: {
borderWidth: 1,
borderRadius: 10,
padding: 10,
marginTop: 10,
marginBottom: 10,
borderColor: 'grey',
},
button: {
backgroundColor: UiColors.background.blue,
padding: 12,
borderRadius: 6,
alignItems: 'center',
marginTop: 10,
},
buttonText: {
color: 'white',
fontSize: 18,
},
});
export default signin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment