Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

Reducer

import jwt_decode from "jwt-decode";
const initState = {
  loading: false,
  signUpErrors: [],
  loginErrors: [],
  token: "",
  user: "",
};

const verifyToken = (token) => {
  const decodeToken = jwt_decode(token);
  const expireIn = new Date(decodeToken.exp * 1000);
  if (new Date() > expireIn) {
    localStorage.removeItem("MyToken");
  } else {
    return decodeToken;
  }
};
const token = localStorage.getItem("MyToken");
if (token) {
  const decoded = verifyToken(token);
  initState.token = token;
  const { userData } = decoded;
  initState.user = userData;
}
const AuthReducer = (state = initState, action) => {
  if (action.type === "SET_LOADER") {
    return { ...state, loading: true };
  } else if (action.type === "CLOSE_LOADER") {
    return { ...state, loading: false };
  } else if (action.type === "SIGNUP_ERRORS") {
    return { ...state, signUpErrors: action.signupError };
  } else if (action.type === "SET_TOKEN") {
    const decoded = verifyToken(action.token);
    const { userData } = decoded;
    return {
      ...state,
      token: action.token,
      user: userData,
      signUpErrors: "",
      loginErrors: "",
    };
  } else if (action.type === "LOGOUT") {
    return { ...state, token: "", user: "" };
  } else if (action.type === "LOGIN_ERRORS") {
    return { ...state, loginErrors: action.loginErrors };
  } else {
    return state;
  }
};
export default AuthReducer;
Source by developer.mozilla.org #
 
PREVIOUS NEXT
Tagged: #Reducer
ADD COMMENT
Topic
Name
5+5 =