Skip to content

Commit

Permalink
refactor: refactored useAuth to avoid nested then()
Browse files Browse the repository at this point in the history
  • Loading branch information
Anush008 committed Apr 27, 2023
1 parent 0570c3e commit 5c12058
Showing 1 changed file with 37 additions and 39 deletions.
76 changes: 37 additions & 39 deletions src/hooks/useAuth.ts
Original file line number Diff line number Diff line change
@@ -1,52 +1,50 @@
import { useEffect, useState } from "react"
import { OPEN_SAUCED_AUTH_TOKEN_KEY, OPEN_SAUCED_SESSION_ENDPOINT } from "../constants"
import { cachedFetch } from "../utils/cache"
import { useEffect, useState } from "react";
import { OPEN_SAUCED_AUTH_TOKEN_KEY, OPEN_SAUCED_SESSION_ENDPOINT } from "../constants";
import { cachedFetch } from "../utils/cache";

const removeTokenFromStorage = () => {
return new Promise((resolve, reject) => {

chrome.storage.sync.remove(OPEN_SAUCED_AUTH_TOKEN_KEY, () => {
resolve(true)
})
})
}
const removeTokenFromStorage = async () => new Promise(resolve => {
chrome.storage.sync.remove(OPEN_SAUCED_AUTH_TOKEN_KEY, () => {
resolve(true);
});
});

export const useAuth = () => {
const [authToken, setAuthToken] = useState<null | string>(null)
const [user, setUser] = useState<null | { id: string, user_name: string }>(null)
const [isTokenValid, setIsTokenValid] = useState<boolean|null>(null)
const [authToken, setAuthToken] = useState<null | string>(null);
const [user, setUser] = useState<null | { id: string, user_name: string }>(null);
const [isTokenValid, setIsTokenValid] = useState<boolean|null>(null);

useEffect(() => {
chrome.storage.sync.get([OPEN_SAUCED_AUTH_TOKEN_KEY], (result) => {
chrome.storage.sync.get([OPEN_SAUCED_AUTH_TOKEN_KEY], async result => {
if (result[OPEN_SAUCED_AUTH_TOKEN_KEY]) {
setAuthToken(result[OPEN_SAUCED_AUTH_TOKEN_KEY])
//get account data
cachedFetch(OPEN_SAUCED_SESSION_ENDPOINT, {
expireInSeconds: 2 * 60 * 60, // 2 hours
setAuthToken(result[OPEN_SAUCED_AUTH_TOKEN_KEY]);

const resp = await cachedFetch(OPEN_SAUCED_SESSION_ENDPOINT, {
expireInSeconds: 2 * 60 * 60,
headers: {
Authorization: `Bearer ${result[OPEN_SAUCED_AUTH_TOKEN_KEY]}`,
Accept: 'application/json',
Accept: "application/json",
},
}).then((resp) => {
if (!resp.ok) {
console.log('error getting user info')
removeTokenFromStorage().then(() => {
setAuthToken(null)
setUser(null)
setIsTokenValid(false)
})
}
return resp.json()
})
.then((json) => {
setUser(json)
setIsTokenValid(true)
});

if (!resp.ok) {
removeTokenFromStorage().then(() => {
setAuthToken(null);
setUser(null);
setIsTokenValid(false);
return null;
})
.catch(console.error);
} else {
const json = await resp.json();

setUser(json);
setIsTokenValid(true);
}
} else {
setIsTokenValid(false)
setIsTokenValid(false);
}
});
}, [])
}, []);

return { authToken, user, isTokenValid }
}
return { authToken, user, isTokenValid };
};

0 comments on commit 5c12058

Please sign in to comment.