Created
December 29, 2022 13:44
-
-
Save DevGW/774d832fd345aed59887fb002e8f6138 to your computer and use it in GitHub Desktop.
React :: DataContext.js
This file contains 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 from "react"; | |
import CreateDataContext from "./CreateDataContext"; | |
import AsyncStorage from '@react-native-async-storage/async-storage'; | |
const authReducer = (state, action) => { | |
switch (action.type) { | |
case 'add_error': { | |
return { ...state, errorMessage: action.payload }; | |
} | |
case 'clear_error': { | |
return { ...state, errorMessage: null } | |
} | |
case 'set_data': { | |
return { ...state, data: action.payload } | |
} | |
default: { | |
return state; | |
} | |
} | |
}; | |
const storeData = async (data) => { | |
try { | |
console.log('storing data....'); | |
const jsonValue = JSON.stringify(data); | |
console.log(jsonValue); | |
await AsyncStorage.setItem('@data', jsonValue) | |
} catch (e) { | |
// saving error | |
console.log('error storing data: '); | |
console.log(e); | |
} | |
} | |
const getData = async (dispatch) => { | |
try { | |
const jsonValue = await AsyncStorage.getItem('@data') | |
data = jsonValue != null ? JSON.parse(jsonValue) : null | |
if (data) { | |
console.log('data found'); | |
console.log(data); | |
await dispatch({type : 'set_data', payload : data}); | |
return true; | |
} | |
else { | |
console.log('no data'); | |
return false; | |
} | |
} catch (e) { | |
// error reading value | |
console.log('error getting data'); | |
console.log(e); | |
} | |
} | |
const clearErrors = (dispatch) => { | |
dispatch({ type: 'add_error', payload: null}) | |
} | |
export const { Provider, Context } = CreateDataContext( | |
authReducer, | |
{ signin, signout, hasToken, signup, resetPassword, resetPasswordWithToken, getColors }, | |
{ isLoggedIn: false, errorMessage: '', credentials: {} }, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment