dailylog 08-05-21

1 minute read

Storing the Token

  1. Add AsyncStorage npm install @react-native-async-storage/async-storage
  2. Import AsyncStorage to AuthContext import AsyncStorage from '@react-native-async-storage/async-storage';
  3. In our signup function, after the response, use AsyncStorage to setItem await AsyncStorage.setItem('token', response.data.token);
  4. We want to update our token in state so we will have to DISPATCH an action…
    1. Add another case to our authReducer switch statements (e.g. case: signup)
    2. 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}
  5. 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.',
      });
    }
  };

Tags:

Updated: