Skip to content

Commit

Permalink
feat(use-user): added refresh interval and tab sync
Browse files Browse the repository at this point in the history
  • Loading branch information
aprendendofelipe committed Dec 26, 2022
1 parent 46f09e9 commit 8829fe5
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions pages/interface/hooks/useUser/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createContext, useCallback, useContext, useEffect, useState } from 'rea

const userEndpoint = '/api/v1/user';
const sessionEndpoint = '/api/v1/sessions';
const refreshInterval = 600000; // 10 minutes

const UserContext = createContext();

Expand All @@ -24,6 +25,7 @@ export function UserProvider({ children }) {
features: responseBody.features,
tabcoins: responseBody.tabcoins,
tabcash: responseBody.tabcash,
cacheTime: Date.now(),
};

setUser(fetchedUser);
Expand Down Expand Up @@ -51,6 +53,19 @@ export function UserProvider({ children }) {
})();
}, [fetchUser]);

useEffect(() => {
if (isLoading) return;

function onFocus() {
const cachedUser = JSON.parse(localStorage.getItem('user'));
setUser(cachedUser);
if (refreshInterval < Date.now() - cachedUser?.cacheTime) fetchUser();
}
addEventListener('focus', onFocus);

return () => removeEventListener('focus', onFocus);
}, [fetchUser, isLoading]);

const logout = useCallback(async () => {
try {
const response = await fetch(sessionEndpoint, {
Expand Down

0 comments on commit 8829fe5

Please sign in to comment.