Skip to content

Instantly share code, notes, and snippets.

@DevGW
Created December 29, 2022 13:44
Show Gist options
  • Save DevGW/774d832fd345aed59887fb002e8f6138 to your computer and use it in GitHub Desktop.
Save DevGW/774d832fd345aed59887fb002e8f6138 to your computer and use it in GitHub Desktop.
React :: DataContext.js
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