@replyke/core
Version:
Replyke: Build interactive apps with social features like comments, votes, feeds, user lists, notifications, and more.
54 lines • 2.56 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = useSwitchAccount;
const react_1 = require("react");
const hooks_1 = require("../../store/hooks");
const accountsSlice_1 = require("../../store/slices/accountsSlice");
const authSlice_1 = require("../../store/slices/authSlice");
const userSlice_1 = require("../../store/slices/userSlice");
const authThunks_1 = require("../../store/slices/authThunks");
const baseApi_1 = require("../../store/api/baseApi");
const useProject_1 = __importDefault(require("../projects/useProject"));
function useSwitchAccount() {
const dispatch = (0, hooks_1.useReplykeDispatch)();
const { projectId } = (0, useProject_1.default)();
const accounts = (0, hooks_1.useReplykeSelector)(accountsSlice_1.selectAccounts);
const activeAccountId = (0, hooks_1.useReplykeSelector)(accountsSlice_1.selectActiveAccountId);
const [isSwitching, setIsSwitching] = (0, react_1.useState)(false);
const [error, setError] = (0, react_1.useState)(null);
const switchAccount = (0, react_1.useCallback)(async ({ userId }) => {
if (!projectId)
throw new Error("No projectId available");
if (userId === activeAccountId)
return;
if (!accounts[userId])
throw new Error(`Account ${userId} not found`);
setIsSwitching(true);
setError(null);
try {
dispatch((0, authSlice_1.resetAuth)());
dispatch((0, userSlice_1.clearUser)());
dispatch(baseApi_1.baseApi.util.resetApiState());
dispatch((0, accountsSlice_1.setActiveAccount)(userId));
dispatch((0, authSlice_1.setTokens)({
accessToken: null,
refreshToken: accounts[userId].refreshToken,
}));
dispatch((0, authSlice_1.setInitialized)(false));
await dispatch((0, authThunks_1.requestNewAccessTokenThunk)({ projectId }));
dispatch((0, authSlice_1.setInitialized)(true));
}
catch (err) {
setError(err instanceof Error ? err.message : "Failed to switch account");
dispatch((0, authSlice_1.setInitialized)(true));
}
finally {
setIsSwitching(false);
}
}, [dispatch, projectId, accounts, activeAccountId]);
return { switchAccount, isSwitching, error };
}
//# sourceMappingURL=useSwitchAccount.js.map