Last active
May 18, 2020 04:28
-
-
Save jdltechworks/5a1946a284b7cb1af32bab2e8bb55849 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { createContext, useReducer, useEffect, useCallback } from 'react' | |
import storage from '@react-native-community/async-storage' | |
import authReducer from 'resources/reducers/auth' | |
export const AuthContext = createContext({}) | |
const AuthProvider = ({ children }) => { | |
const [fields, dispatch] = useReducer(authReducer, { | |
name: { error: null }, | |
email: { error: null }, | |
password: { error: null }, | |
incomplete: true, | |
autheticated: false, | |
password_confirmation: { error: null }, | |
token: null, | |
}) | |
const getToken = useCallback(async () => { | |
const value = await storage.getItem('token') | |
value && dispatch({ type: 'LOGGED_IN', payload: value }) | |
}) | |
useEffect(() => { | |
getToken() | |
}, []) | |
const handleChange = (type, text) => { | |
dispatch({ type: 'TEXT_CHANGE', payload: { [type] : text } }) | |
} | |
return ( | |
<AuthContext.Provider value={{ fields, handleChange, dispatch, storage }}> | |
{children} | |
</AuthContext.Provider> | |
) | |
} | |
export default AuthProvider |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import authValidator from 'resources/validator/auth' | |
import keys from 'lodash/keys' | |
const authReducer = (state, action) => { | |
switch (action.type) { | |
case 'LOGIN': { | |
} | |
case 'LOGGED_IN': { | |
return { | |
...state, | |
token: action.payload | |
} | |
} | |
case 'LOGIN_FAILED': { | |
} | |
case 'TEXT_CHANGE': { | |
const [key] = keys(action.payload) | |
const value = action.payload[key] | |
const validatorElems = authValidator[key] | |
const pattern = new RegExp(validatorElems.pattern, 'i') | |
if (pattern.test(value)) { | |
return { | |
...state, | |
...action.payload, | |
incomplete: false, | |
} | |
} | |
return { | |
...state, | |
[key]: { ...state[key], error: `Invalid ${key} ` }, | |
incomplete: true, | |
} | |
} | |
default: | |
return {} | |
} | |
} | |
export default authReducer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment