Skip to content

Instantly share code, notes, and snippets.

@azeezat
Created August 7, 2021 01:34
Show Gist options
  • Save azeezat/7b7520540215e33b0e702eba5baea383 to your computer and use it in GitHub Desktop.
Save azeezat/7b7520540215e33b0e702eba5baea383 to your computer and use it in GitHub Desktop.
import React, { useEffect, useMemo, useReducer } from "react";
import {
setItemInLocalStorage,
getUserDetailsFromStorage,
clearLocalStorage,
} from "../../helpers";
import { USER_TOKEN } from "../../constants";
import { AuthContext, initialAuthState } from "./AuthContext";
import { useActivityContext } from "../activity/ActivityContext";
import { userReducer } from "../../reducers";
import { UPDATE_USER_CONTEXT, CLEAR_USER_CONTEXT } from "../../types";
export const AuthProvider = (props) => {
const user = getUserDetailsFromStorage();
const [state, dispatch] = useReducer(
userReducer,
user ? user : initialAuthState
);
const updateUserContext = (user) => {
dispatch({
type: UPDATE_USER_CONTEXT,
payload: user,
});
};
const clearUserContext = () => {
dispatch({
type: CLEAR_USER_CONTEXT,
payload: initialAuthState,
});
};
//All consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes
//to get around this, we use useMemo hook which would memoize the value object.
//It would only be re-created when user value changes.
const value = useMemo(
() => ({
user: state,
updateUserContext,
clearUserContext,
}),
[updateUserContext]
);
//-----------------------------------//
//-----Set User in local Storage----//
useEffect(() => {
setItemInLocalStorage(USER_TOKEN, state);
}, [user]);
//---------------------------------------//
//-----check expiry to update context----//
const checkExpiry = (expiryDate) => {
const now = new Date();
if (now.getTime() > expiryDate) {
return true;
}
return false;
};
const { toggleNotify } = useActivityContext();
let isExpired = checkExpiry(state.expiry);
useEffect(() => {
if (isExpired) {
toggleNotify({
icon: "announcement",
title: "Session Expiry!",
message: "Your Session has expired",
color: "danger",
static: true,
});
clearLocalStorage();
clearUserContext();
}
return () => {
// cleanup;
};
}, [isExpired]);
return (
<AuthContext.Provider value={value}>{props.children}</AuthContext.Provider>
);
};
export default AuthProvider;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment