dailylog 08-05-21
Storing the Token
- Add AsyncStorage
npm install @react-native-async-storage/async-storage
- Import AsyncStorage to AuthContext
import AsyncStorage from '@react-native-async-storage/async-storage';
- In our signup function, after the response, use AsyncStorage to setItem
await AsyncStorage.setItem('token', response.data.token);
- We want to update our token in state so we will have to DISPATCH an action…
- Add another case to our authReducer switch statements (e.g. case: signup)
- We’re going to return our state object and use destructuring to simply update that single piece of state – TOKEN, so it will be {…state, token: action.payload}
- NOW, we can update our export const to return a token instead of
isSignedIn: false
because if there is no token, we know user is not signed in
QUICK REFACTOR taking advantage of IMPLICIT RETURNS
IF our function is only returning ONE THING, we can take advantage of implicit returns with our arrow statements
e.g.
const add = (a, b) => {
return a + b;
};
// SAME AS
const add = (a, b) => a + b;
const signup = (dispatch) => {
return async ({ email, password }) => {
try {
const response = await trackerApi.post('/signup', { email, password });
await AsyncStorage.setItem('token', response.data.token);
dispatch({ type: 'signup', payload: response.data.token });
console.log(response);
} catch (err) {
dispatch({
type: 'add_error',
payload: 'Oh no! Something went wrong with signup.',
});
}
};
};
// TURNS INTO
const signup =
(dispatch) =>
async ({ email, password }) => {
try {
const response = await trackerApi.post('/signup', { email, password });
await AsyncStorage.setItem('token', response.data.token);
dispatch({ type: 'signup', payload: response.data.token });
console.log(response);
} catch (err) {
dispatch({
type: 'add_error',
payload: 'Oh no! Something went wrong with signup.',
});
}
};