Created
April 4, 2021 21:20
-
-
Save pupato13/7c16d155689aebddb407c020c3fbc369 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 createDataContext from "./createDataContext"; | |
import trackerApi from "../api/trackerApi"; | |
import AsyncStorage from "@react-native-community/async-storage"; | |
import { navigate } from "../navigationRef"; | |
const TOKEN_KEY = "@TrackersApp"; | |
const ACTIONS = { | |
ADD_ERROR: "add_error", | |
SIGN_UP: "sign_up", | |
}; | |
const authReducer = (state, action) => { | |
switch (action.type) { | |
case ACTIONS.ADD_ERROR: | |
return { ...state, errorMessage: action.payload }; | |
case ACTIONS.SIGN_UP: | |
return { token: action.payload, errorMessage: "" }; | |
default: | |
return state; | |
} | |
}; | |
const signUp = (dispatch) => async ({ email, password }) => { | |
try { | |
const response = await trackerApi.post("/signup", { | |
email, | |
password, | |
}); | |
console.log(response); | |
await AsyncStorage.setItem(TOKEN_KEY, response.data.token); | |
dispatch({ | |
type: ACTIONS.SIGN_UP, | |
payload: response.data.token, | |
}); | |
navigate("TrackList"); | |
} catch (error) { | |
dispatch({ | |
type: ACTIONS.ADD_ERROR, | |
payload: "Something went wrong with Sign Up!", | |
}); | |
} | |
}; | |
const signIn = (dispatch) => { | |
return async ({ email, password }) => { | |
// go to api and signIn | |
}; | |
}; | |
const signOut = (dispatch) => { | |
return () => { | |
// manage async storage | |
}; | |
}; | |
export const { Provider, Context } = createDataContext( | |
authReducer, | |
{ signUp, signIn, signOut }, | |
{ | |
token: null, | |
errorMessage: "", | |
} | |
); |
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 } from "react"; | |
export default (reducer, actions, defaultValue) => { | |
const Context = 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 }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment