Skip to content

Instantly share code, notes, and snippets.

@lukecurtis93
Last active April 6, 2020 05:53
Show Gist options
  • Save lukecurtis93/a814fe0c821a7a76d79b1bf54b73e336 to your computer and use it in GitHub Desktop.
Save lukecurtis93/a814fe0c821a7a76d79b1bf54b73e336 to your computer and use it in GitHub Desktop.
Context
import { Provider as AuthProvider } from "./src/context/AuthContext";
return loaded ? (
<AuthProvider>
<NavigationContainer
theme={scheme === "dark" || darkModeSelected ? DarkTheme : LightTheme}
>
<Stack.Navigator>
<Stack.Screen
name="ResolveAuth"
component={ResolveAuthScreen}
options={{
headerMode: "none",
header: () => null
}}
/>
</NavigationContainer>
</AuthProvider>
import { AsyncStorage } from "react-native";
import createDataContext from "./createDataContext";
import nofomo from "../api/nofomo";
const authReducer = (state, action) => {
switch (action.type) {
case "signin":
return { ...state, user: action.payload };
case "signout":
return { user: "" };
default:
return state;
}
};
const logout = dispatch => async () => {
await AsyncStorage.removeItem("token");
await AsyncStorage.removeItem("user");
dispatch({ type: "signout" });
};
const getUser = dispatch => async () => {
const token = await AsyncStorage.getItem("token");
if (token) {
const user = await nofomo.get("user").catch(error => {
//There was an error, log them out and we can get them to try again
logout();
});
if (user) {
await AsyncStorage.setItem("user", JSON.stringify(user.data));
dispatch({ type: "signin", payload: user.data });
}
}
};
export const { Provider, Context } = createDataContext(
authReducer,
{ login, logout, getUser, deepLinkLogin },
{
user: {}
}
);
import React, { useReducer } from "react";
export default (reducer, actions, defaultValue) => {
const Context = React.createContext();
const Provider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, defaultValue);
const boundActions = {};
for (let key in actions) {
boundActions[key] = actions[key](dispatch);
}
return (
<Context.Provider value={{ state, ...boundActions }}>
{children}
</Context.Provider>
);
};
return { Context, Provider };
};
import React, { useEffect, useContext } from "react";
import { Context as AuthContext } from "../context/AuthContext";
import { useNavigation } from "@react-navigation/native";
const ResolveAuthScreen = () => {
const navigation = useNavigation();
const {
state: { user },
getUser
} = useContext(AuthContext);
useEffect(() => {
getUser().then(() => {
if (user.location_id) {
navigation.navigate("Main");
} else if (user.id && !user.location_id) {
navigation.navigate("Onboarding");
} else {
navigation.navigate("Landing");
}
});
}, []);
return null;
};
export default ResolveAuthScreen;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment