Skip to content

Instantly share code, notes, and snippets.

@adamclasic
Created November 12, 2022 11:09
Show Gist options
  • Save adamclasic/c9d2cc33aa5c8658e7d2426e9dac8c79 to your computer and use it in GitHub Desktop.
Save adamclasic/c9d2cc33aa5c8658e7d2426e9dac8c79 to your computer and use it in GitHub Desktop.
React User Auth front end
import { createContext, useReducer, useEffect } from 'react';
import { getCookie } from '../utils/functions';
const AuthContext = createContext();
const authReducer = (state, action) => {
switch (action.type) {
case 'LOGIN':
return { user: action.payload };
case 'LOGOUT':
return { user: null };
default:
return state;
}
};
const AuthContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(authReducer, {
user: null,
});
useEffect(() => {
const user = JSON.parse(getCookie('auth-token'));
if (user) {
dispatch({ type: 'LOGIN', payload: user });
}
}, []);
console.log('AuthContext state:', state);
return (
<AuthContext.Provider value={{ ...state, dispatch }}>
{children}
</AuthContext.Provider>
);
};
export { authReducer, AuthContext, AuthContextProvider };
// ./src/context/AuthContext.js
function setCookie(name, value, houres) {
// eslint-disable-next-line
Date.prototype.addHours = function (h) {
this.setTime(this.getTime() + h * 60 * 60 * 1000);
return this;
};
let expires = '';
if (houres) {
const oneHourFromNow = new Date().addHours(1);
expires = '; expires=' + oneHourFromNow.toUTCString();
}
document.cookie = name + '=' + (value || '') + expires + '; path=/';
}
function getCookie(name) {
let nameEQ = name + '=';
let ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
export { getCookie, setCookie, eraseCookie };
// ./src/utils/
import { AuthContext } from '../context/AuthContext';
import { useContext } from 'react';
export const useAuthContext = () => {
const context = useContext(AuthContext);
if (!context) {
throw Error('useAuthContext must be used inside an AuthContextProvider');
}
return context;
};
// ./src/hooks/
import { useState } from 'react';
import axios from 'axios';
import { useAuthContext } from './useAuthContext';
import { setCookie } from '../utils/functions';
export const useLogin = () => {
const API_KEY = 'XiRXJK3ugQmG0hVQ';
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(null);
const { dispatch } = useAuthContext();
const login = async (email, password) => {
setIsLoading(true);
setError(null);
const raw = {
email,
password,
};
const headers = {
'Content-Type': 'application/json',
'x-general-key': API_KEY,
};
let response;
try {
response = await axios.post(
'https://api-test-technique-production.up.railway.app/users/login',
JSON.stringify(raw),
{ headers: headers }
);
console.log('response', response);
const { data, status } = response;
if (status !== 200) {
throw response?.data?.message || response.message;
}
if (status === 200) {
setCookie('auth-token', JSON.stringify(data), 1);
dispatch({ type: 'LOGIN', payload: data });
setIsLoading(false);
setError(false);
}
} catch (err) {
console.log('err', err);
setIsLoading(false);
setError(
err?.response?.data?.message ||
err?.response?.data?.error ||
'Something went wrong!'
);
}
};
return { login, isLoading, error };
};
import { useAuthContext } from './useAuthContext';
import { eraseCookie } from '../utils/functions';
export const useLogout = () => {
const { dispatch } = useAuthContext();
const logout = () => {
localStorage.removeItem('auth-token');
eraseCookie('auth-token');
dispatch({ type: 'LOGOUT' });
};
return { logout };
};
import { useState } from 'react';
import axios from 'axios';
import { useAuthContext } from './useAuthContext';
import { setCookie } from '../utils/functions';
export const useSignup = () => {
const API_KEY = 'XiRXJK3ugQmG0hVQ';
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(null);
const { dispatch } = useAuthContext();
const signup = async (email, password) => {
setIsLoading(true);
setError(null);
var raw = {
email,
password,
};
const headers = {
'Content-Type': 'application/json',
'x-general-key': API_KEY,
};
let response;
try {
response = await axios.post(
'https://api-test-technique-production.up.railway.app/users/register',
JSON.stringify(raw),
{ headers: headers }
);
console.log('response', response);
const { data, status } = response;
if (status !== 200) {
throw response?.data?.message || response.message;
}
if (status === 200) {
setCookie('auth-token', JSON.stringify(data), 1);
dispatch({ type: 'LOGIN', payload: data });
setIsLoading(false);
setError(false);
}
} catch (error) {
console.log(error);
setIsLoading(false);
setError(error?.response?.data?.message || 'Something went wrong!');
}
};
return { signup, isLoading, error };
};
@adamclasic
Copy link
Author

uses Axios

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment