Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Get rid of Redux in favour of Context API

Blue Mouse7f71aaa91d98
diff --git a/web/app/App.tsx b/web/app/App.tsx
index c7258c2e0..fc0e17458 100644
--- a/web/app/App.tsx
+++ b/web/app/App.tsx
@@ -4,61 +4,23 @@ import _some from 'lodash/some'
import _startsWith from 'lodash/startsWith'
import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { useLocation, Outlet } from 'react-router'
import 'dayjs/locale/uk'
import { Toaster } from 'sonner'
import Footer from '~/components/Footer'
import Header from '~/components/Header'
-import { isBrowser, isSelfhosted } from '~/lib/constants'
-import { authActions } from '~/lib/reducers/auth'
-import { StateType, useAppDispatch } from '~/lib/store'
-import { getAccessToken } from '~/utils/accessToken'
-import { logout } from '~/utils/auth'
import routesPath from '~/utils/routes'
import { getPageMeta } from '~/utils/server'
-import { authMe, getInstalledExtensions } from './api'
import { useTheme } from './providers/ThemeProvider'
-interface AppProps {
- ssrAuthenticated: boolean
-}
-
const TITLE_BLACKLIST = ['/projects/', '/captchas/', '/blog']
-const App = ({ ssrAuthenticated }: AppProps) => {
- const dispatch = useAppDispatch()
+const App = () => {
const { pathname } = useLocation()
const { t } = useTranslation('common')
- const { loading } = useSelector((state: StateType) => state.auth)
- const reduxAuthenticated = useSelector((state: StateType) => state.auth.authenticated)
const { theme } = useTheme()
- const accessToken = getAccessToken()
- const authenticated = isBrowser ? (loading ? !!accessToken : reduxAuthenticated) : ssrAuthenticated
-
- useEffect(() => {
- void (async () => {
- if (accessToken && !reduxAuthenticated) {
- try {
- const { user, totalMonthlyEvents } = await authMe()
- dispatch(authActions.authSuccessful({ ...user, totalMonthlyEvents }))
-
- if (!isSelfhosted) {
- const extensions = await getInstalledExtensions()
- dispatch(authActions.setExtensions(extensions))
- }
- } catch (reason) {
- dispatch(authActions.logout())
- logout()
- console.error(`[ERROR] Error while getting user: ${reason}`)
- }
- }
-
- dispatch(authActions.finishLoading())
- })()
- }, [reduxAuthenticated]) // eslint-disable-line
useEffect(() => {
if (_some(TITLE_BLACKLIST, (page) => _startsWith(pathname, page))) {
@@ -89,9 +51,7 @@ const App = ({ ssrAuthenticated }: AppProps) => {
return (
<>
- {!_includes(routesWithOutHeader, pathname) && !isReferralPage && !isProjectViewPage ? (
- <Header authenticated={authenticated} />
- ) : null}
+ {!_includes(routesWithOutHeader, pathname) && !isReferralPage && !isProjectViewPage ? <Header /> : null}
<Outlet />
<Toaster
theme={theme}
@@ -99,7 +59,7 @@ const App = ({ ssrAuthenticated }: AppProps) => {
duration: 5000,
}}
/>
- {!isReferralPage && !isProjectViewPage ? <Footer authenticated={authenticated} /> : null}
+ {!isReferralPage && !isProjectViewPage ? <Footer /> : null}
</>
)
}
diff --git a/web/app/api/index.ts b/web/app/api/index.ts
index ecdf30603..b523a0588 100644
--- a/web/app/api/index.ts
+++ b/web/app/api/index.ts
@@ -9,12 +9,10 @@ import { Alerts } from '~/lib/models/Alerts'
import { Auth } from '~/lib/models/Auth'
import { Metainfo } from '~/lib/models/Metainfo'
import { Role } from '~/lib/models/Organisation'
-import { Project, Overall, LiveStats, Funnel } from '~/lib/models/Project'
+import { Project, Overall, LiveStats, Funnel, Extension } from '~/lib/models/Project'
import { Stats } from '~/lib/models/Stats'
import { Subscriber } from '~/lib/models/Subscriber'
import { User, FeatureFlag } from '~/lib/models/User'
-import { authActions } from '~/lib/reducers/auth'
-import { store } from '~/lib/store'
import { Filter, ProjectViewCustomEvent } from '~/pages/Project/View/interfaces/traffic'
import { getAccessToken, removeAccessToken, setAccessToken } from '~/utils/accessToken'
import { logout } from '~/utils/auth'
@@ -40,8 +38,8 @@ const refreshAuthLogic = (failedRequest: { response: AxiosResponse }) =>
return Promise.resolve()
})
.catch((error) => {
- store.dispatch(authActions.logout())
logout()
+ // If user session is invalid, this rejection will be thrown to authMe in AuthProvider and will reset user there too
return Promise.reject(error)
})
@@ -63,20 +61,15 @@ api.interceptors.request.use(
},
)
-export const authMe = () =>
- api
- .get('user/me')
- .then(
- (
- response,
- ): {
- user: User
- totalMonthlyEvents: number
- } => response.data,
- )
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
+export const authMe = (config?: AxiosRequestConfig) =>
+ api.get('user/me', config).then(
+ (
+ response,
+ ): {
+ user: User
+ totalMonthlyEvents: number
+ } => response.data,
+ )
export const logoutApi = (refreshToken: string | null) =>
axios
@@ -1000,10 +993,17 @@ export const deleteApiKey = () =>
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
})
-export const getInstalledExtensions = (limit = 100, offset = 0) =>
+export const getInstalledExtensions = (limit = 100, offset = 0, config?: AxiosRequestConfig) =>
api
- .get(`/extensions/installed?limit=${limit}&offset=${offset}`)
- .then((response) => response.data)
+ .get(`/extensions/installed?limit=${limit}&offset=${offset}`, config)
+ .then(
+ (
+ response,
+ ): {
+ count: number
+ extensions: Extension[]
+ } => response.data,
+ )
.catch((error) => {
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
})
diff --git a/web/app/components/DashboardLockedBanner.tsx b/web/app/components/DashboardLockedBanner.tsx
index 2837719e4..fb00fd40e 100644
--- a/web/app/components/DashboardLockedBanner.tsx
+++ b/web/app/components/DashboardLockedBanner.tsx
@@ -1,17 +1,18 @@
import { LockClosedIcon } from '@heroicons/react/24/outline'
import { memo, useState, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { DashboardBlockReason } from '~/lib/models/User'
-import { StateType } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Modal from '~/ui/Modal'
const DashboardLockedBanner = () => {
const { t } = useTranslation('common')
- const dashboardBlockReason = useSelector((state: StateType) => state.auth.user.dashboardBlockReason)
+ const { user } = useAuth()
const [showMoreInfoModal, setShowMoreInfoModal] = useState(false)
+ const dashboardBlockReason = user?.dashboardBlockReason
+
const message = useMemo(() => {
if (dashboardBlockReason === DashboardBlockReason.exceeding_plan_limits) {
return t('project.locked.descExceedingTier')
diff --git a/web/app/components/EventsRunningOutBanner.tsx b/web/app/components/EventsRunningOutBanner.tsx
index 6c6b6d8bf..1ed4de584 100644
--- a/web/app/components/EventsRunningOutBanner.tsx
+++ b/web/app/components/EventsRunningOutBanner.tsx
@@ -1,10 +1,9 @@
import { ExclamationTriangleIcon, XMarkIcon } from '@heroicons/react/24/outline'
import { memo, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { LOW_EVENTS_WARNING, SHOW_BANNER_AT_PERC } from '~/lib/constants'
-import { StateType } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Modal from '~/ui/Modal'
import { shouldShowLowEventsBanner } from '~/utils/auth'
import { setCookie } from '~/utils/cookie'
@@ -13,18 +12,23 @@ import { secondsTillNextMonth } from '~/utils/generic'
const EventsRunningOutBanner = () => {
const { t } = useTranslation('common')
const [shouldShowBanner, setShouldShowBanner] = useState(false)
- const { dashboardBlockReason, totalMonthlyEvents, maxEventsCount } = useSelector(
- (state: StateType) => state.auth.user,
- )
const [showMoreInfoModal, setShowMoreInfoModal] = useState(false)
+ const { user, totalMonthlyEvents } = useAuth()
+
useEffect(() => {
+ if (!user) {
+ return
+ }
+
+ const { maxEventsCount } = user
+
if (!totalMonthlyEvents || !maxEventsCount) {
return
}
setShouldShowBanner(shouldShowLowEventsBanner(totalMonthlyEvents, maxEventsCount))
- }, [totalMonthlyEvents, maxEventsCount])
+ }, [user, totalMonthlyEvents])
const closeHandler = () => {
setShouldShowBanner(false)
@@ -33,7 +37,7 @@ const EventsRunningOutBanner = () => {
setCookie(LOW_EVENTS_WARNING, 1, maxAge)
}
- if (!shouldShowBanner || dashboardBlockReason) {
+ if (!shouldShowBanner || user?.dashboardBlockReason) {
return null
}
diff --git a/web/app/components/Footer/index.tsx b/web/app/components/Footer/index.tsx
index df8de9b9d..222688412 100644
--- a/web/app/components/Footer/index.tsx
+++ b/web/app/components/Footer/index.tsx
@@ -20,6 +20,7 @@ import {
DISCORD_URL,
CAPTCHA_URL,
} from '~/lib/constants'
+import { useAuth } from '~/providers/AuthProvider'
import Flag from '~/ui/Flag'
import LinkedIn from '~/ui/icons/LinkedIn'
import SwetrixLogo from '~/ui/icons/SwetrixLogo'
@@ -166,11 +167,11 @@ const SelfHostedFooter = () => {
}
interface FooterProps {
- authenticated?: boolean
showDBIPMessage?: boolean
}
-const Footer = ({ authenticated, showDBIPMessage }: FooterProps) => {
+const Footer = ({ showDBIPMessage }: FooterProps) => {
+ const { isAuthenticated } = useAuth()
const { t } = useTranslation('common')
const year = new Date().getFullYear()
@@ -288,7 +289,7 @@ const Footer = ({ authenticated, showDBIPMessage }: FooterProps) => {
<h3 className='text-sm font-semibold tracking-wider text-white uppercase'>{t('footer.legal')}</h3>
<ul className='mt-4 space-y-4'>
{_map(navigation.legal, (func) => {
- const { key, href, internal } = func(authenticated)
+ const { key, href, internal } = func(isAuthenticated)
return (
<li key={key}>
diff --git a/web/app/components/Header/index.tsx b/web/app/components/Header/index.tsx
index 8095b0c6d..fe6f321a1 100644
--- a/web/app/components/Header/index.tsx
+++ b/web/app/components/Header/index.tsx
@@ -26,7 +26,6 @@ import _startsWith from 'lodash/startsWith'
import { GaugeIcon, ChartPieIcon, BugIcon, PuzzleIcon, PhoneIcon } from 'lucide-react'
import { memo, Fragment, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { Link } from 'react-router'
import {
@@ -38,14 +37,11 @@ import {
CAPTCHA_URL,
isDisableMarketingPages,
} from '~/lib/constants'
-import { User } from '~/lib/models/User'
-import { authActions } from '~/lib/reducers/auth'
-import { useAppDispatch, StateType } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
import Dropdown from '~/ui/Dropdown'
import Flag from '~/ui/Flag'
import SwetrixLogo from '~/ui/icons/SwetrixLogo'
-import { logout } from '~/utils/auth'
import routes from '~/utils/routes'
dayjs.extend(utc)
@@ -266,7 +262,8 @@ const ThemeMenu = () => {
)
}
-const ProfileMenu = ({ user, logoutHandler }: { user: User; logoutHandler: () => void }) => {
+const ProfileMenu = ({ logoutHandler }: { logoutHandler: () => void }) => {
+ const { user } = useAuth()
const {
t,
i18n: { language },
@@ -477,20 +474,19 @@ const Separator = () => (
)
const AuthedHeader = ({
- user,
rawStatus,
status,
logoutHandler,
colourBackground,
openMenu,
}: {
- user: User
rawStatus: string | number
status: string
logoutHandler: () => void
colourBackground: boolean
openMenu: () => void
}) => {
+ const { user } = useAuth()
const { theme, setTheme } = useTheme()
const { t } = useTranslation('common')
@@ -570,7 +566,7 @@ const AuthedHeader = ({
</div>
<div className='ml-1 hidden flex-wrap items-center justify-center space-y-1 space-x-2 sm:space-y-0 lg:ml-10 lg:flex lg:space-x-4'>
<ThemeMenu />
- <ProfileMenu user={user} logoutHandler={logoutHandler} />
+ <ProfileMenu logoutHandler={logoutHandler} />
</div>
<div className='flex items-center justify-center space-x-3 lg:hidden'>
{/* Theme switch */}
@@ -756,18 +752,16 @@ const NotAuthedHeader = ({
}
interface HeaderProps {
- authenticated: boolean
refPage?: boolean
transparent?: boolean
}
-const Header = ({ authenticated, refPage, transparent }: HeaderProps) => {
+const Header = ({ refPage, transparent }: HeaderProps) => {
const {
t,
i18n: { language },
} = useTranslation('common')
- const dispatch = useAppDispatch()
- const { user } = useSelector((state: StateType) => state.auth)
+ const { isAuthenticated, user, logout } = useAuth()
const [mobileMenuOpen, setMobileMenuOpen] = useState(false)
const { theme, setTheme } = useTheme()
@@ -809,7 +803,6 @@ const Header = ({ authenticated, refPage, transparent }: HeaderProps) => {
const logoutHandler = () => {
setMobileMenuOpen(false)
- dispatch(authActions.logout())
logout()
}
@@ -820,9 +813,8 @@ const Header = ({ authenticated, refPage, transparent }: HeaderProps) => {
return (
<Popover>
{/* Computer / Laptop / Tablet layout header */}
- {authenticated ? (
+ {isAuthenticated ? (
<AuthedHeader
- user={user}
rawStatus={rawStatus || ''}
status={status || ''}
logoutHandler={logoutHandler}
@@ -982,7 +974,7 @@ const Header = ({ authenticated, refPage, transparent }: HeaderProps) => {
)}
</Disclosure>
) : null}
- {!isSelfhosted && authenticated && user?.planCode === 'trial' ? (
+ {!isSelfhosted && isAuthenticated && user?.planCode === 'trial' ? (
<Link
to={routes.billing}
onClick={() => setMobileMenuOpen(false)}
@@ -1001,7 +993,7 @@ const Header = ({ authenticated, refPage, transparent }: HeaderProps) => {
{status}
</Link>
) : null}
- {!isSelfhosted && authenticated && user?.planCode === 'none' ? (
+ {!isSelfhosted && isAuthenticated && user?.planCode === 'none' ? (
<Link
to={routes.billing}
onClick={() => setMobileMenuOpen(false)}
@@ -1011,7 +1003,7 @@ const Header = ({ authenticated, refPage, transparent }: HeaderProps) => {
{t('billing.inactive')}
</Link>
) : null}
- {!isSelfhosted && authenticated && user?.planCode !== 'none' && user?.planCode !== 'trial' ? (
+ {!isSelfhosted && isAuthenticated && user?.planCode !== 'none' && user?.planCode !== 'trial' ? (
<Link
to={routes.billing}
onClick={() => setMobileMenuOpen(false)}
@@ -1021,7 +1013,7 @@ const Header = ({ authenticated, refPage, transparent }: HeaderProps) => {
{t('common.billing')}
</Link>
) : null}
- {!isSelfhosted && !isDisableMarketingPages && !authenticated ? (
+ {!isSelfhosted && !isDisableMarketingPages && !isAuthenticated ? (
<Link
to={`${routes.main}#pricing`}
onClick={() => setMobileMenuOpen(false)}
@@ -1060,7 +1052,7 @@ const Header = ({ authenticated, refPage, transparent }: HeaderProps) => {
>
{t('common.docs')}
</a>
- {authenticated ? (
+ {isAuthenticated ? (
<Link
to={routes.dashboard}
onClick={() => setMobileMenuOpen(false)}
@@ -1071,7 +1063,7 @@ const Header = ({ authenticated, refPage, transparent }: HeaderProps) => {
) : null}
</div>
<div className='space-y-2 py-6'>
- {authenticated ? (
+ {isAuthenticated ? (
<>
<Link
to={routes.user_settings}
diff --git a/web/app/components/marketing/Pricing.tsx b/web/app/components/marketing/Pricing.tsx
index a35263da3..9ba0196f5 100644
--- a/web/app/components/marketing/Pricing.tsx
+++ b/web/app/components/marketing/Pricing.tsx
@@ -7,12 +7,11 @@ import _isNil from 'lodash/isNil'
import _map from 'lodash/map'
import React, { memo, useState, useEffect } from 'react'
import { Trans, useTranslation } from 'react-i18next'
-import { useSelector, useDispatch } from 'react-redux'
import { Link } from 'react-router'
import { ClientOnly } from 'remix-utils/client-only'
import { toast } from 'sonner'
-import { authMe, previewSubscriptionUpdate, changeSubscriptionPlan, getPaymentMetainfo } from '~/api'
+import { previewSubscriptionUpdate, changeSubscriptionPlan, getPaymentMetainfo } from '~/api'
import {
CONTACT_EMAIL,
paddleLanguageMapping,
@@ -24,14 +23,12 @@ import {
TRIAL_DAYS,
} from '~/lib/constants'
import { DEFAULT_METAINFO, Metainfo } from '~/lib/models/Metainfo'
-import { authActions } from '~/lib/reducers/auth'
-import { AppDispatch, StateType } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
import { Badge } from '~/ui/Badge'
import Button from '~/ui/Button'
import Loader from '~/ui/Loader'
import Modal from '~/ui/Modal'
-import { logout } from '~/utils/auth'
import routes from '~/utils/routes'
const getPaidFeatures = (t: any, tier: any) => {
@@ -61,8 +58,7 @@ const Pricing = ({ authenticated, isBillingPage, lastEvent }: PricingProps) => {
t,
i18n: { language },
} = useTranslation('common')
- const dispatch = useDispatch<AppDispatch>()
- const { user } = useSelector((state: StateType) => state.auth)
+ const { user, loadUser } = useAuth()
const { theme } = useTheme()
const [metainfo, setMetainfo] = useState<Metainfo>(DEFAULT_METAINFO)
@@ -84,12 +80,12 @@ const Pricing = ({ authenticated, isBillingPage, lastEvent }: PricingProps) => {
const [billingFrequency, setBillingFrequency] = useState(user?.billingFrequency || BillingFrequency.monthly)
const PLAN_CODES_ARRAY = authenticated
- ? _includes(STANDARD_PLANS, user.planCode)
+ ? _includes(STANDARD_PLANS, user?.planCode)
? STANDARD_PLANS
- : [user.planCode, ...STANDARD_PLANS]
+ : [user?.planCode, ...STANDARD_PLANS]
: STANDARD_PLANS
- const [selectedTier, setSelectedTier] = useState<any>(authenticated ? PLAN_LIMITS[user.planCode] : PLAN_LIMITS.hobby)
+ const [selectedTier, setSelectedTier] = useState(PLAN_LIMITS[user?.planCode || 'hobby'])
const planFeatures = getPaidFeatures(t, selectedTier)
const currency = CURRENCIES[currencyCode]
@@ -124,16 +120,7 @@ const Pricing = ({ authenticated, isBillingPage, lastEvent }: PricingProps) => {
if (data.event === 'Checkout.Complete') {
// giving some time to the API to process tier upgrate via Paddle webhook
setTimeout(async () => {
- try {
- const { user } = await authMe()
-
- dispatch(authActions.authSuccessful(user))
- dispatch(authActions.finishLoading())
- } catch (reason) {
- dispatch(authActions.logout())
- logout()
- console.error(`[ERROR] Error while getting user after subscription update: ${reason}`)
- }
+ await loadUser()
toast.success(t('apiNotifications.subscriptionUpdated'))
}, 3000)
@@ -146,7 +133,7 @@ const Pricing = ({ authenticated, isBillingPage, lastEvent }: PricingProps) => {
}
lastEventHandler(lastEvent)
- }, [lastEvent, dispatch, t])
+ }, [lastEvent, t, loadUser])
const loadSubUpdatePreview = async (planId: number) => {
setIsNewPlanConfirmationModalOpened(true)
@@ -161,6 +148,10 @@ const Pricing = ({ authenticated, isBillingPage, lastEvent }: PricingProps) => {
}
const onPlanChange = async (tier: { planCode: string; name: string; pid: string; ypid: string }) => {
+ if (!user) {
+ return
+ }
+
const isSelectingDifferentPlan =
user.planCode !== tier.planCode ||
user.billingFrequency !== billingFrequency ||
@@ -220,16 +211,7 @@ const Pricing = ({ authenticated, isBillingPage, lastEvent }: PricingProps) => {
try {
await changeSubscriptionPlan(newPlanId as number)
- try {
- const { user } = await authMe()
-
- dispatch(authActions.authSuccessful(user))
- dispatch(authActions.finishLoading())
- } catch (reason) {
- dispatch(authActions.logout())
- logout()
- console.error(`[ERROR] Error while getting user after subscription update: ${reason}`)
- }
+ await loadUser()
toast.success(t('apiNotifications.subscriptionUpdated'))
closeUpdateModal(true)
@@ -241,25 +223,29 @@ const Pricing = ({ authenticated, isBillingPage, lastEvent }: PricingProps) => {
}
const downgradeHandler = (tier: { planCode: string; name: string; pid: string; ypid: string }) => {
+ if (!user) {
+ return
+ }
+
if (planCodeLoading === null && user.planCode !== tier.planCode) {
setDowngradeTo(tier)
setShowDowngradeModal(true)
}
}
- const userPlancodeID = PLAN_LIMITS[user.planCode]?.index
+ const userPlancodeID = user?.planCode ? PLAN_LIMITS[user.planCode]?.index : 0
const planCodeID = selectedTier.index
- const downgrade = !user.cancellationEffectiveDate && planCodeID < userPlancodeID
+ const downgrade = !user?.cancellationEffectiveDate && planCodeID < userPlancodeID
let action: string
- if (user.cancellationEffectiveDate || ['free', 'trial', 'none'].includes(user.planCode)) {
+ if (user?.cancellationEffectiveDate || ['free', 'trial', 'none'].includes(user?.planCode || '')) {
action = t('pricing.subscribe')
} else if (planCodeID > userPlancodeID) {
action = t('pricing.upgrade')
} else if (downgrade) {
action = t('pricing.downgrade')
- } else if (user.billingFrequency === billingFrequency) {
+ } else if (user?.billingFrequency === billingFrequency) {
action = t('pricing.yourPlan')
} else if (billingFrequency === BillingFrequency.monthly) {
action = t('pricing.switchToMonthly')
@@ -349,7 +335,7 @@ const Pricing = ({ authenticated, isBillingPage, lastEvent }: PricingProps) => {
onChange={onSelectPlanChange}
/>
<div className='relative mt-5 divide-y rounded-2xl border ring-1 ring-gray-200 dark:ring-slate-700'>
- {user.planCode === selectedTier.planCode ? (
+ {user?.planCode === selectedTier.planCode ? (
<div className='absolute top-0 left-5 translate-y-px transform border-none'>
<div className='flex -translate-y-1/2 transform justify-center bg-gray-50 dark:bg-slate-900'>
<Badge label={t('pricing.currentPlan')} colour='indigo' />
@@ -382,17 +368,16 @@ const Pricing = ({ authenticated, isBillingPage, lastEvent }: PricingProps) => {
{authenticated ? (
<Button
+ // @ts-expect-error TODO fix this later
onClick={() => (downgrade ? downgradeHandler(selectedTier) : onPlanChange(selectedTier))}
type='button'
className='mt-2 sm:mt-0'
loading={planCodeLoading === selectedTier.planCode}
disabled={
planCodeLoading !== null ||
- (selectedTier.planCode === user.planCode &&
- (user.billingFrequency === billingFrequency ||
- user.planCode === 'free' ||
- user.planCode === 'trial' ||
- user.planCode === 'none'))
+ (selectedTier.planCode === user?.planCode &&
+ (user?.billingFrequency === billingFrequency ||
+ ['free', 'trial', 'none'].includes(user?.planCode || '')))
}
primary
large
diff --git a/web/app/hoc/protected.tsx b/web/app/hoc/protected.tsx
index 143a43d0b..a101b6638 100644
--- a/web/app/hoc/protected.tsx
+++ b/web/app/hoc/protected.tsx
@@ -1,9 +1,7 @@
import { useEffect, useRef } from 'react'
-import { useSelector } from 'react-redux'
import { useNavigate } from 'react-router'
-import { StateType } from '~/lib/store'
-import { getAccessToken } from '~/utils/accessToken'
+import { useAuth } from '~/providers/AuthProvider'
import routes from '~/utils/routes'
interface AuthParamType {
@@ -25,13 +23,10 @@ export const auth = {
}
export const withAuthentication = <P extends PropsType>(WrappedComponent: any, authParam: AuthParamType) => {
- const accessToken = getAccessToken()
-
const WithAuthentication = (props: P) => {
const { shouldBeAuthenticated, redirectPath } = authParam
- const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)
const navigate = useNavigate()
- const authenticated = loading ? !!accessToken : reduxAuthenticated
+ const { isAuthenticated } = useAuth()
// We need to use ref to avoid 404 errors - https://github.com/remix-run/react-router/pull/12853
const navigating = useRef(false)
@@ -41,13 +36,13 @@ export const withAuthentication = <P extends PropsType>(WrappedComponent: any, a
return
}
- if (shouldBeAuthenticated !== authenticated) {
+ if (shouldBeAuthenticated !== isAuthenticated) {
navigate(redirectPath)
navigating.current = true
}
// TODO: Investigate this later. https://github.com/remix-run/react-router/discussions/8465
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [authenticated, shouldBeAuthenticated])
+ }, [isAuthenticated, shouldBeAuthenticated])
// if (!selector) {
// return null
diff --git a/web/app/hooks/useFeatureFlag.ts b/web/app/hooks/useFeatureFlag.ts
index 9776a6cf3..a3927898c 100644
--- a/web/app/hooks/useFeatureFlag.ts
+++ b/web/app/hooks/useFeatureFlag.ts
@@ -1,10 +1,8 @@
-import { useSelector } from 'react-redux'
-
import { FeatureFlag } from '~/lib/models/User'
-import { StateType } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
const useFeatureFlag = (flag: FeatureFlag): boolean => {
- const { user } = useSelector((state: StateType) => state.auth)
+ const { user } = useAuth()
if (!user?.featureFlags) {
return false
diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.ts
index 06142f2be..923221dc8 100644
--- a/web/app/lib/models/Project.ts
+++ b/web/app/lib/models/Project.ts
@@ -101,3 +101,27 @@ export interface CaptchaProject extends Project {
isCaptchaProject: true
isCaptchaEnabled: true
}
+
+export interface Extension {
+ id: string
+ name: string
+ description: string
+ version: string
+ status: string
+ price: number
+ mainImage: string
+ additionalImages: string[]
+ fileURL: string
+ companyLink: string | null
+ createdAt: string
+ updatedAt: string
+ tags: string[]
+ owner: {
+ nickname: string
+ }
+ category: {
+ id: number
+ name: string
+ }
+ usersQuantity: number
+}
diff --git a/web/app/lib/models/User.ts b/web/app/lib/models/User.ts
index 8664c5e99..99082be30 100644
--- a/web/app/lib/models/User.ts
+++ b/web/app/lib/models/User.ts
@@ -75,7 +75,4 @@ export interface User {
dashboardBlockReason: DashboardBlockReason
isAccountBillingSuspended: boolean
organisationMemberships: OrganisationMembership[]
-
- // Does not come from User directly; we need it for the EventsRunningOutBanner
- totalMonthlyEvents: number
}
diff --git a/web/app/lib/reducers/auth.ts b/web/app/lib/reducers/auth.ts
deleted file mode 100644
index afece4ff8..000000000
--- a/web/app/lib/reducers/auth.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { createSlice, PayloadAction } from '@reduxjs/toolkit'
-
-import { User } from '../models/User'
-
-interface AuthState {
- user: User
- authenticated: boolean
- loading: boolean
- dontRemember: boolean
- extensions: any[]
-}
-
-const initialState: AuthState = {
- user: {} as User,
- authenticated: false,
- loading: true,
- dontRemember: false,
-
- // TODO: Only load extensions per project; migrate this to useCurrentProject
- extensions: [],
-}
-
-const authSlice = createSlice({
- name: 'auth',
- initialState,
- reducers: {
- finishLoading: (state) => {
- state.loading = false
- },
- authSuccessful: (state, { payload }: PayloadAction<User>) => {
- state.user = payload
- state.authenticated = true
- },
- logout: (state) => {
- state.user = {} as User
- state.authenticated = false
- },
- setDontRemember: (state, { payload }: PayloadAction<boolean>) => {
- state.dontRemember = payload
- },
- mergeUser: (state, { payload }: PayloadAction<Partial<User>>) => {
- state.user = { ...state.user, ...payload }
- },
- setUser: (state, { payload }: PayloadAction<User>) => {
- state.user = payload
- },
- setExtensions(state, { payload }: PayloadAction<any[]>) {
- state.extensions = payload
- },
- },
-})
-
-export const authActions = authSlice.actions
-
-export default authSlice.reducer
diff --git a/web/app/lib/store/index.ts b/web/app/lib/store/index.ts
deleted file mode 100644
index 6b11e2e07..000000000
--- a/web/app/lib/store/index.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { combineReducers, configureStore } from '@reduxjs/toolkit'
-import { useDispatch } from 'react-redux'
-
-import { isDevelopment } from '~/lib/constants'
-
-import authSlice from '../reducers/auth'
-
-const rootReducer = combineReducers({
- auth: authSlice,
-})
-
-export const store = configureStore({
- reducer: rootReducer,
- devTools: isDevelopment,
-})
-
-export type AppDispatch = typeof store.dispatch
-export const useAppDispatch: () => AppDispatch = useDispatch
-export type StateType = ReturnType<typeof store.getState>
diff --git a/web/app/pages/Auth/CheckYourInbox/CheckYourInbox.tsx b/web/app/pages/Auth/CheckYourInbox/CheckYourInbox.tsx
index ee8c9db61..0d314922c 100644
--- a/web/app/pages/Auth/CheckYourInbox/CheckYourInbox.tsx
+++ b/web/app/pages/Auth/CheckYourInbox/CheckYourInbox.tsx
@@ -1,21 +1,17 @@
import { EnvelopeIcon } from '@heroicons/react/24/outline'
import { useMemo, useEffect } from 'react'
import { useTranslation, Trans } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { useNavigate } from 'react-router'
import { withAuthentication } from '~/hoc/protected'
-import { authActions } from '~/lib/reducers/auth'
-import { StateType, useAppDispatch } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Loader from '~/ui/Loader'
-import { logout } from '~/utils/auth'
import routes from '~/utils/routes'
const CheckYourInbox = () => {
const { t } = useTranslation('common')
- const { loading, user } = useSelector((state: StateType) => state.auth)
+ const { user, isLoading, logout } = useAuth()
const navigate = useNavigate()
- const dispatch = useAppDispatch()
const message = useMemo(() => {
return t('auth.confirm.linkSent', { email: user?.email })
@@ -28,7 +24,7 @@ const CheckYourInbox = () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [user?.isActive])
- if (loading) {
+ if (isLoading) {
return (
<div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>
<Loader />
@@ -67,7 +63,6 @@ const CheckYourInbox = () => {
role='button'
className='cursor-pointer font-medium text-indigo-600 hover:underline dark:text-indigo-400'
onClick={() => {
- dispatch(authActions.logout())
logout()
}}
/>
diff --git a/web/app/pages/Auth/Signin/Signin.tsx b/web/app/pages/Auth/Signin/Signin.tsx
index 72a1258f8..4b69fe068 100644
--- a/web/app/pages/Auth/Signin/Signin.tsx
+++ b/web/app/pages/Auth/Signin/Signin.tsx
@@ -7,14 +7,13 @@ import { useTranslation, Trans } from 'react-i18next'
import { Link, useNavigate, useSearchParams } from 'react-router'
import { toast } from 'sonner'
-import { generateSSOAuthURL, getInstalledExtensions, getJWTBySSOHash, login, submit2FA } from '~/api'
+import { generateSSOAuthURL, getJWTBySSOHash, login, submit2FA } from '~/api'
import GithubAuth from '~/components/GithubAuth'
import GoogleAuth from '~/components/GoogleAuth'
import { withAuthentication, auth } from '~/hoc/protected'
import { isSelfhosted, REFERRAL_COOKIE, TRIAL_DAYS } from '~/lib/constants'
import { SSOProvider } from '~/lib/models/Auth'
-import { authActions } from '~/lib/reducers/auth'
-import { useAppDispatch } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Button from '~/ui/Button'
import Checkbox from '~/ui/Checkbox'
import Input from '~/ui/Input'
@@ -34,7 +33,6 @@ interface SigninForm {
const HASH_CHECK_FREQUENCY = 1000
const Signin = () => {
- const dispatch = useAppDispatch()
const navigate = useNavigate()
const [searchParams] = useSearchParams()
const { t } = useTranslation('common')
@@ -53,6 +51,7 @@ const Signin = () => {
const [isTwoFARequired, setIsTwoFARequired] = useState(searchParams.get('show_2fa_screen') === 'true')
const [twoFACode, setTwoFACode] = useState('')
const [twoFACodeError, setTwoFACodeError] = useState<string | null>(null)
+ const { setUser, setTotalMonthlyEvents } = useAuth()
const validate = () => {
const allErrors = {} as {
@@ -119,20 +118,17 @@ const Signin = () => {
if (user.isTwoFactorAuthenticationEnabled) {
setAccessToken(accessToken, true)
setRefreshToken(refreshToken)
- dispatch(authActions.mergeUser(user))
+ setUser(user)
setIsTwoFARequired(true)
setIsLoading(false)
return
}
- dispatch(authActions.authSuccessful({ ...user, totalMonthlyEvents }))
+ setUser(user)
+ setTotalMonthlyEvents(totalMonthlyEvents)
setAccessToken(accessToken, false)
setRefreshToken(refreshToken)
- await loadExtensions()
-
- dispatch(authActions.finishLoading())
-
navigate(routes.dashboard)
return
@@ -152,15 +148,6 @@ const Signin = () => {
}
}
- const loadExtensions = async () => {
- if (isSelfhosted) {
- return
- }
-
- const extensions = await getInstalledExtensions()
- dispatch(authActions.setExtensions(extensions))
- }
-
const onSubmit = async (data: SigninForm) => {
if (isLoading) {
return
@@ -173,29 +160,25 @@ const Signin = () => {
const { user, accessToken, refreshToken, totalMonthlyEvents } = await login(_omit(data, ['dontRemember']))
- dispatch(authActions.setDontRemember(dontRemember))
-
if (user.isTwoFactorAuthenticationEnabled) {
setAccessToken(accessToken, true)
setRefreshToken(refreshToken, true)
- dispatch(authActions.mergeUser(user))
+ setUser(user)
+ setTotalMonthlyEvents(totalMonthlyEvents)
setIsTwoFARequired(true)
setIsLoading(false)
return
}
- dispatch(authActions.authSuccessful({ ...user, totalMonthlyEvents }))
+ setUser(user)
+ setTotalMonthlyEvents(totalMonthlyEvents)
setAccessToken(accessToken, dontRemember)
setRefreshToken(refreshToken)
- await loadExtensions()
-
setIsLoading(false)
} catch (reason) {
toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
setIsLoading(false)
- } finally {
- dispatch(authActions.finishLoading())
}
}
@@ -203,28 +186,29 @@ const Signin = () => {
e.preventDefault()
e.stopPropagation()
- if (!isLoading) {
- setIsLoading(true)
-
- try {
- const { accessToken, refreshToken, user } = await submit2FA(twoFACode)
- removeAccessToken()
- removeRefreshToken()
- setAccessToken(accessToken)
- setRefreshToken(refreshToken)
- await loadExtensions()
- dispatch(authActions.authSuccessful(user))
- } catch (reason) {
- if (_isString(reason)) {
- toast.error(reason)
- }
- console.error(`[ERROR] Failed to authenticate with 2FA: ${reason}`)
- setTwoFACodeError(t('profileSettings.invalid2fa'))
- }
+ if (isLoading) {
+ return
+ }
- setTwoFACode('')
- setIsLoading(false)
+ setIsLoading(true)
+
+ try {
+ const { accessToken, refreshToken, user } = await submit2FA(twoFACode)
+ removeAccessToken()
+ removeRefreshToken()
+ setAccessToken(accessToken)
+ setRefreshToken(refreshToken)
+ setUser(user)
+ } catch (reason) {
+ if (_isString(reason)) {
+ toast.error(reason)
+ }
+ console.error(`[ERROR] Failed to authenticate with 2FA: ${reason}`)
+ setTwoFACodeError(t('profileSettings.invalid2fa'))
}
+
+ setTwoFACode('')
+ setIsLoading(false)
}
const handleInput = ({ target }: { target: HTMLInputElement }) => {
diff --git a/web/app/pages/Auth/Signup/Signup.tsx b/web/app/pages/Auth/Signup/Signup.tsx
index 521711920..49aefe4cd 100644
--- a/web/app/pages/Auth/Signup/Signup.tsx
+++ b/web/app/pages/Auth/Signup/Signup.tsx
@@ -3,7 +3,6 @@ import _keys from 'lodash/keys'
import _size from 'lodash/size'
import React, { useState, useEffect } from 'react'
import { useTranslation, Trans } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { Link, useNavigate } from 'react-router'
import { toast } from 'sonner'
@@ -12,13 +11,12 @@ import GithubAuth from '~/components/GithubAuth'
import GoogleAuth from '~/components/GoogleAuth'
import { HAVE_I_BEEN_PWNED_URL, REFERRAL_COOKIE, TRIAL_DAYS } from '~/lib/constants'
import { SSOProvider } from '~/lib/models/Auth'
-import { authActions } from '~/lib/reducers/auth'
-import { StateType, useAppDispatch } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Button from '~/ui/Button'
import Checkbox from '~/ui/Checkbox'
import Input from '~/ui/Input'
import Tooltip from '~/ui/Tooltip'
-import { getAccessToken, setAccessToken } from '~/utils/accessToken'
+import { setAccessToken } from '~/utils/accessToken'
import { trackCustom } from '~/utils/analytics'
import { deleteCookie, getCookie } from '~/utils/cookie'
import { delay, openBrowserWindow } from '~/utils/generic'
@@ -38,8 +36,6 @@ interface SignupForm {
const HASH_CHECK_FREQUENCY = 1000
const Signup = () => {
- const dispatch = useAppDispatch()
- const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)
const { t } = useTranslation('common')
const [form, setForm] = useState<SignupForm>({
email: '',
@@ -59,8 +55,7 @@ const Signup = () => {
const [beenSubmitted, setBeenSubmitted] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const navigate = useNavigate()
- const accessToken = getAccessToken()
- const authenticated = loading ? !!accessToken : reduxAuthenticated
+ const { isAuthenticated, setUser, setTotalMonthlyEvents } = useAuth()
const validate = () => {
const allErrors = {} as {
@@ -101,11 +96,11 @@ const Signup = () => {
}, [form]) // eslint-disable-line
useEffect(() => {
- if (authenticated && !beenSubmitted) {
+ if (isAuthenticated && !beenSubmitted) {
navigate(routes.dashboard)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [authenticated, beenSubmitted])
+ }, [isAuthenticated, beenSubmitted])
const onSubmit = async (data: SignupForm) => {
if (isLoading) {
@@ -130,8 +125,7 @@ const Signup = () => {
deleteCookie(REFERRAL_COOKIE)
}
- dispatch(authActions.authSuccessful(user))
- dispatch(authActions.setDontRemember(dontRemember))
+ setUser(user)
setAccessToken(accessToken, dontRemember)
setRefreshToken(refreshToken)
setIsLoading(false)
@@ -143,8 +137,6 @@ const Signup = () => {
} catch (reason) {
toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
setIsLoading(false)
- } finally {
- dispatch(authActions.finishLoading())
}
}
@@ -181,18 +173,18 @@ const Signup = () => {
if (user.isTwoFactorAuthenticationEnabled) {
setAccessToken(accessToken, true)
setRefreshToken(refreshToken)
- dispatch(authActions.mergeUser(user))
+ setUser(user)
+ setTotalMonthlyEvents(totalMonthlyEvents)
navigate(`${routes.signin}?show_2fa_screen=true`)
setIsLoading(false)
return
}
- dispatch(authActions.authSuccessful({ ...user, totalMonthlyEvents }))
+ setUser(user)
+ setTotalMonthlyEvents(totalMonthlyEvents)
setAccessToken(accessToken, false)
setRefreshToken(refreshToken)
- dispatch(authActions.finishLoading())
-
navigate(routes.dashboard)
return
diff --git a/web/app/pages/Auth/VerifyEmail/index.tsx b/web/app/pages/Auth/VerifyEmail/index.tsx
index ce1fcf81e..fd1967d19 100644
--- a/web/app/pages/Auth/VerifyEmail/index.tsx
+++ b/web/app/pages/Auth/VerifyEmail/index.tsx
@@ -2,20 +2,19 @@ import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/solid'
import _isString from 'lodash/isString'
import { useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
-import { useDispatch } from 'react-redux'
import { useParams, Link } from 'react-router'
import { verifyEmail } from '~/api'
-import { authActions } from '~/lib/reducers/auth'
+import { useAuth } from '~/providers/AuthProvider'
import Loader from '~/ui/Loader'
import routes from '~/utils/routes'
const VerifyEmail = () => {
const { t } = useTranslation('common')
- const dispatch = useDispatch()
const { id } = useParams()
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
+ const { mergeUser } = useAuth()
useEffect(() => {
setLoading(true)
@@ -29,11 +28,10 @@ const VerifyEmail = () => {
const verify = async () => {
try {
await verifyEmail({ id })
- dispatch(authActions.mergeUser({ isActive: true }))
+ mergeUser({ isActive: true })
} catch (reason: any) {
setError(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
} finally {
- dispatch(authActions.finishLoading())
setLoading(false)
}
}
diff --git a/web/app/pages/Billing/index.tsx b/web/app/pages/Billing/index.tsx
index 9e183497c..96162d163 100644
--- a/web/app/pages/Billing/index.tsx
+++ b/web/app/pages/Billing/index.tsx
@@ -5,23 +5,15 @@ import utc from 'dayjs/plugin/utc'
import _round from 'lodash/round'
import { memo, useMemo, useState, useEffect } from 'react'
import { useTranslation, Trans } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { toast } from 'sonner'
import { getPaymentMetainfo, getUsageInfo } from '~/api'
import DashboardLockedBanner from '~/components/DashboardLockedBanner'
import { withAuthentication, auth } from '~/hoc/protected'
-import {
- isSelfhosted,
- PADDLE_JS_URL,
- PADDLE_VENDOR_ID,
- CONTACT_EMAIL,
- paddleLanguageMapping,
- isBrowser,
-} from '~/lib/constants'
+import { isSelfhosted, PADDLE_JS_URL, PADDLE_VENDOR_ID, CONTACT_EMAIL, paddleLanguageMapping } from '~/lib/constants'
import { DEFAULT_METAINFO, Metainfo } from '~/lib/models/Metainfo'
import { UsageInfo } from '~/lib/models/Usageinfo'
-import { StateType } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
import Button from '~/ui/Button'
import Loader from '~/ui/Loader'
@@ -35,11 +27,7 @@ import Pricing from '../../components/marketing/Pricing'
dayjs.extend(utc)
dayjs.extend(duration)
-interface BillingProps {
- ssrAuthenticated: boolean
-}
-
-const Billing = ({ ssrAuthenticated }: BillingProps) => {
+const Billing = () => {
const [isCancelSubModalOpened, setIsCancelSubModalOpened] = useState(false)
const [metainfo, setMetainfo] = useState<Metainfo>(DEFAULT_METAINFO)
@@ -47,9 +35,9 @@ const Billing = ({ ssrAuthenticated }: BillingProps) => {
event: string
} | null>(null)
- const { user, loading: authLoading } = useSelector((state: StateType) => state.auth)
+ const { user, isLoading: authLoading } = useAuth()
const { theme } = useTheme()
- const reduxAuthenticated = useSelector((state: StateType) => state.auth.authenticated)
+ const { isAuthenticated } = useAuth()
const [usageInfo, setUsageInfo] = useState<UsageInfo>({
total: 0,
traffic: 0,
@@ -65,7 +53,6 @@ const Billing = ({ ssrAuthenticated }: BillingProps) => {
t,
i18n: { language },
} = useTranslation('common')
- const authenticated = isBrowser ? reduxAuthenticated : ssrAuthenticated
const {
nextBillDate,
planCode,
@@ -74,14 +61,14 @@ const Billing = ({ ssrAuthenticated }: BillingProps) => {
timeFormat,
cancellationEffectiveDate,
subCancelURL,
- maxEventsCount,
- } = user
+ maxEventsCount = 0,
+ } = user || {}
- const isSubscriber = user.planCode !== 'none' && user.planCode !== 'trial' && user.planCode !== 'free'
+ const isSubscriber = !['none', 'trial', 'free'].includes(planCode || '')
const isTrial = planCode === 'trial'
const isNoSub = planCode === 'none'
- const totalUsage = _round((usageInfo.total / maxEventsCount) * 100, 2) || 0
+ const totalUsage = maxEventsCount ? _round((usageInfo.total / maxEventsCount) * 100, 2) : 0
const [isLoading, setIsLoading] = useState(true)
@@ -314,7 +301,7 @@ const Billing = ({ ssrAuthenticated }: BillingProps) => {
<Loader />
) : (
<div className='mt-8 flex flex-col'>
- <Pricing authenticated={authenticated} isBillingPage lastEvent={lastEvent} />
+ <Pricing authenticated={isAuthenticated} isBillingPage lastEvent={lastEvent} />
<div className='mt-2 space-y-2'>
{subUpdateURL && !cancellationEffectiveDate ? (
<Button className='mr-2' onClick={onUpdatePaymentDetails} type='button' primary large>
diff --git a/web/app/pages/Captcha/Settings/CaptchaSettings.tsx b/web/app/pages/Captcha/Settings/CaptchaSettings.tsx
index d2d8553f3..efa5f0293 100644
--- a/web/app/pages/Captcha/Settings/CaptchaSettings.tsx
+++ b/web/app/pages/Captcha/Settings/CaptchaSettings.tsx
@@ -12,7 +12,6 @@ import _split from 'lodash/split'
import { Trash2Icon } from 'lucide-react'
import React, { useState, useEffect, memo } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { Link, useNavigate } from 'react-router'
import { toast } from 'sonner'
@@ -28,7 +27,7 @@ import { withAuthentication, auth } from '~/hoc/protected'
import { useRequiredParams } from '~/hooks/useRequiredParams'
import { TITLE_SUFFIX } from '~/lib/constants'
import { CaptchaProject } from '~/lib/models/Project'
-import { StateType } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Button from '~/ui/Button'
import Checkbox from '~/ui/Checkbox'
import Input from '~/ui/Input'
@@ -54,7 +53,7 @@ interface CaptchaSettingsProps {
}
const CaptchaSettings = ({ isSettings }: CaptchaSettingsProps) => {
- const { loading: authLoading } = useSelector((state: StateType) => state.auth)
+ const { isLoading: authLoading } = useAuth()
const { t } = useTranslation('common')
const { id } = useRequiredParams<{
diff --git a/web/app/pages/Captcha/View/ViewCaptcha.tsx b/web/app/pages/Captcha/View/ViewCaptcha.tsx
index 2daa6067e..5b0a84687 100644
--- a/web/app/pages/Captcha/View/ViewCaptcha.tsx
+++ b/web/app/pages/Captcha/View/ViewCaptcha.tsx
@@ -13,7 +13,6 @@ import _startsWith from 'lodash/startsWith'
import { DownloadIcon, RotateCw, SettingsIcon } from 'lucide-react'
import { useState, useEffect, useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { useNavigate, useSearchParams } from 'react-router'
import { ClientOnly } from 'remix-utils/client-only'
@@ -33,11 +32,11 @@ import {
OS_LOGO_MAP_DARK,
DEFAULT_TIMEZONE,
} from '~/lib/constants'
-import { StateType } from '~/lib/store'
import { Panel } from '~/pages/Project/View/Panels'
import { parseFiltersFromUrl } from '~/pages/Project/View/utils/filters'
import { ViewProjectContext } from '~/pages/Project/View/ViewProject'
import { deviceIconMapping, onCSVExportClick } from '~/pages/Project/View/ViewProject.helpers'
+import { useAuth } from '~/providers/AuthProvider'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import { useTheme } from '~/providers/ThemeProvider'
import Dropdown from '~/ui/Dropdown'
@@ -75,7 +74,7 @@ const PageLoader = () => (
const ViewCaptcha = () => {
const { id, project, preferences, updatePreferences } = useCurrentProject()
- const { loading: authLoading, user } = useSelector((state: StateType) => state.auth)
+ const { user, isLoading: authLoading } = useAuth()
const { theme } = useTheme()
const {
@@ -116,7 +115,7 @@ const ViewCaptcha = () => {
const [searchParams] = useSearchParams()
- const timeFormat = useMemo(() => user.timeFormat || TimeFormat['12-hour'], [user])
+ const timeFormat = useMemo(() => user?.timeFormat || TimeFormat['12-hour'], [user])
const [ref, size] = useSize() as any
const rotateXAxias = useMemo(() => size.width > 0 && size.width < 500, [size])
const [chartType, setChartType] = useState<string>((getItem('chartType') as string) || chartTypes.line)
diff --git a/web/app/pages/Dashboard/Dashboard.tsx b/web/app/pages/Dashboard/Dashboard.tsx
index ae3b5c9f4..59cd5aa27 100644
--- a/web/app/pages/Dashboard/Dashboard.tsx
+++ b/web/app/pages/Dashboard/Dashboard.tsx
@@ -7,7 +7,6 @@ import _size from 'lodash/size'
import { StretchHorizontal as StretchHorizontalIcon, LayoutGrid as LayoutGridIcon } from 'lucide-react'
import React, { useState, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { Link, useLoaderData, useSearchParams } from 'react-router'
import { ClientOnly } from 'remix-utils/client-only'
@@ -21,7 +20,7 @@ import useFeatureFlag from '~/hooks/useFeatureFlag'
import { isSelfhosted, LIVE_VISITORS_UPDATE_INTERVAL } from '~/lib/constants'
import { Overall, Project } from '~/lib/models/Project'
import { FeatureFlag } from '~/lib/models/User'
-import { StateType } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Modal from '~/ui/Modal'
import Pagination from '~/ui/Pagination'
import { setCookie } from '~/utils/cookie'
@@ -43,7 +42,7 @@ const DASHBOARD_VIEW = {
const Dashboard = () => {
const { viewMode: defaultViewMode } = useLoaderData<any>()
- const { user, loading: authLoading } = useSelector((state: StateType) => state.auth)
+ const { user, isLoading: authLoading } = useAuth()
const showPeriodSelector = useFeatureFlag(FeatureFlag['dashboard-period-selector'])
const showTabs = useFeatureFlag(FeatureFlag['dashboard-analytics-tabs'])
const isHostnameNavigationEnabled = useFeatureFlag(FeatureFlag['dashboard-hostname-cards'])
@@ -141,7 +140,7 @@ const Dashboard = () => {
const _viewMode = isAboveLgBreakpoint ? viewMode : 'grid'
const onNewProject = (e: React.MouseEvent<HTMLAnchorElement>) => {
- if (user.isActive || isSelfhosted) {
+ if (user?.isActive || isSelfhosted) {
return
}
diff --git a/web/app/pages/Dashboard/ProjectCard.tsx b/web/app/pages/Dashboard/ProjectCard.tsx
index e74acfe0c..e3d3de4cd 100644
--- a/web/app/pages/Dashboard/ProjectCard.tsx
+++ b/web/app/pages/Dashboard/ProjectCard.tsx
@@ -9,7 +9,6 @@ import _round from 'lodash/round'
import _size from 'lodash/size'
import React, { useState, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { Link } from 'react-router'
import { toast } from 'sonner'
@@ -17,8 +16,7 @@ import { acceptProjectShare } from '~/api'
import useFeatureFlag from '~/hooks/useFeatureFlag'
import { OverallObject, Project } from '~/lib/models/Project'
import { FeatureFlag } from '~/lib/models/User'
-import { authActions } from '~/lib/reducers/auth'
-import { StateType, useAppDispatch } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import { Badge, BadgeProps } from '~/ui/Badge'
import Spin from '~/ui/icons/Spin'
import Modal from '~/ui/Modal'
@@ -90,11 +88,12 @@ export const ProjectCard = ({ live, project, overallStats, activePeriod, activeT
const isHostnameNavigationEnabled = useFeatureFlag(FeatureFlag['dashboard-hostname-cards'])
const showPeriodSelector = useFeatureFlag(FeatureFlag['dashboard-period-selector'])
- const { user } = useSelector((state: StateType) => state.auth)
+ const { user, mergeUser } = useAuth()
- const dispatch = useAppDispatch()
-
- const shareId = useMemo(() => _find(project.share, (item) => item.user.id === user.id)?.id, [project.share, user.id])
+ const shareId = useMemo(
+ () => _find(project.share, (item) => item.user.id === user?.id)?.id,
+ [project.share, user?.id],
+ )
const { id, name, public: isPublic, active, isTransferring, share, organisation, role } = project
@@ -157,17 +156,15 @@ export const ProjectCard = ({ live, project, overallStats, activePeriod, activeT
await acceptProjectShare(shareId)
- dispatch(
- authActions.mergeUser({
- sharedProjects: user.sharedProjects?.map((item) => {
- if (item.id === shareId) {
- return { ...item, isAccessConfirmed: true }
- }
+ mergeUser({
+ sharedProjects: user?.sharedProjects?.map((item) => {
+ if (item.id === shareId) {
+ return { ...item, isAccessConfirmed: true }
+ }
- return item
- }),
+ return item
}),
- )
+ })
toast.success(t('apiNotifications.acceptInvitation'))
} catch (reason: any) {
diff --git a/web/app/pages/Dashboard/SortSelector.tsx b/web/app/pages/Dashboard/SortSelector.tsx
index c5f70c54d..13e023250 100644
--- a/web/app/pages/Dashboard/SortSelector.tsx
+++ b/web/app/pages/Dashboard/SortSelector.tsx
@@ -5,11 +5,10 @@ import _map from 'lodash/map'
import { ArrowUpDown } from 'lucide-react'
import { Fragment, useEffect, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import useFeatureFlag from '~/hooks/useFeatureFlag'
import { FeatureFlag } from '~/lib/models/User'
-import { StateType } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import { DASHBOARD_TABS } from './Tabs'
@@ -33,7 +32,7 @@ export const SORT_OPTIONS = {
export const SortSelector = ({ activeSort, setActiveSort, isLoading, activeTab }: SortSelectorProps) => {
const { t } = useTranslation('common')
- const { loading: authLoading } = useSelector((state: StateType) => state.auth)
+ const { isLoading: authLoading } = useAuth()
const isHostnameNavigationEnabled = useFeatureFlag(FeatureFlag['dashboard-hostname-cards'])
diff --git a/web/app/pages/ErrorTracking/index.tsx b/web/app/pages/ErrorTracking/index.tsx
index a8dbb7c4c..a320d6616 100644
--- a/web/app/pages/ErrorTracking/index.tsx
+++ b/web/app/pages/ErrorTracking/index.tsx
@@ -2,20 +2,18 @@ import { ArrowRightIcon } from '@heroicons/react/20/solid'
import { ChevronRightIcon } from '@heroicons/react/24/solid'
import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
-import { memo, useEffect, useState } from 'react'
+import { useEffect, useState } from 'react'
import { useTranslation, Trans } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { Link } from 'react-router'
import { ClientOnly } from 'remix-utils/client-only'
import { getLastPost } from '~/api'
import Header from '~/components/Header'
import { DitchGoogle } from '~/components/marketing/DitchGoogle'
-import { ERROR_TRACKING_LIVE_DEMO_URL, isBrowser } from '~/lib/constants'
-import { StateType } from '~/lib/store/index'
+import { ERROR_TRACKING_LIVE_DEMO_URL } from '~/lib/constants'
+import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
import BackgroundSvg from '~/ui/icons/BackgroundSvg'
-import { getAccessToken } from '~/utils/accessToken'
import routesPath from '~/utils/routes'
import Pricing from '../../components/marketing/Pricing'
@@ -28,17 +26,11 @@ const Lines = () => (
</div>
)
-interface ErrorTrackingProps {
- ssrAuthenticated: boolean
-}
-
-const ErrorTracking = ({ ssrAuthenticated }: ErrorTrackingProps) => {
+const ErrorTracking = () => {
const { t } = useTranslation('common')
const { theme } = useTheme()
- const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)
const [lastBlogPost, setLastBlogPost] = useState<Awaited<ReturnType<typeof getLastPost>> | null>(null)
- const accessToken = getAccessToken()
- const authenticated = isBrowser ? (loading ? !!accessToken : reduxAuthenticated) : ssrAuthenticated
+ const { isAuthenticated } = useAuth()
useEffect(() => {
const abortController = new AbortController()
@@ -84,7 +76,7 @@ const ErrorTracking = ({ ssrAuthenticated }: ErrorTrackingProps) => {
}}
/>
</div>
- <Header authenticated={authenticated} transparent />
+ <Header transparent />
<div className='relative mx-auto min-h-[740px] pt-10 pb-5 sm:px-3 lg:px-6 lg:pt-24 xl:px-8'>
<div className='relative z-20 flex flex-row content-between justify-center lg:justify-start 2xl:mr-[14vw] 2xl:justify-center'>
<div className='relative px-4 text-left lg:mt-0 lg:mr-14'>
@@ -234,7 +226,7 @@ const ErrorTracking = ({ ssrAuthenticated }: ErrorTrackingProps) => {
</div>
{/* For now let's hide Pricing for authenticated users on the main page as the Paddle script only loads on the Billing page */}
- {!authenticated ? <Pricing authenticated={false} /> : null}
+ {!isAuthenticated ? <Pricing authenticated={false} /> : null}
<DitchGoogle
screenshot={{
@@ -259,4 +251,4 @@ const ErrorTracking = ({ ssrAuthenticated }: ErrorTrackingProps) => {
)
}
-export default memo(ErrorTracking)
+export default ErrorTracking
diff --git a/web/app/pages/Landings/Marketers.tsx b/web/app/pages/Landings/Marketers.tsx
index 4d03601a3..e4cc0ab55 100644
--- a/web/app/pages/Landings/Marketers.tsx
+++ b/web/app/pages/Landings/Marketers.tsx
@@ -1,31 +1,20 @@
import { ArrowRightIcon } from '@heroicons/react/20/solid'
import _map from 'lodash/map'
import { useTranslation, Trans } from 'react-i18next'
-import { useSelector } from 'react-redux'
-import { Link, useLoaderData } from 'react-router'
+import { Link } from 'react-router'
import Header from '~/components/Header'
import { ComparisonTable } from '~/components/marketing/ComparisonTable'
import { DitchGoogle } from '~/components/marketing/DitchGoogle'
-import { BOOK_A_CALL_URL, DISCORD_URL, isBrowser, LIVE_DEMO_URL } from '~/lib/constants'
-import { StateType } from '~/lib/store'
+import { BOOK_A_CALL_URL, DISCORD_URL, LIVE_DEMO_URL } from '~/lib/constants'
import { useTheme } from '~/providers/ThemeProvider'
-import { getAccessToken } from '~/utils/accessToken'
import routesPath from '~/utils/routes'
-interface LoaderProps {
- isAuth: boolean
-}
-
const INTEGRATIONS_URL = 'https://docs.swetrix.com/integrations'
const Marketers = () => {
- const { isAuth } = useLoaderData<LoaderProps>()
const { t } = useTranslation('common')
const { theme } = useTheme()
- const accessToken = getAccessToken()
- const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)
- const authenticated = isBrowser ? (loading ? !!accessToken : reduxAuthenticated) : isAuth
return (
<main className='bg-white dark:bg-slate-900'>
@@ -59,7 +48,7 @@ const Marketers = () => {
}}
/>
</div>
- <Header authenticated={authenticated} transparent />
+ <Header transparent />
<div className='relative mx-auto min-h-[740px] pt-10 pb-5 sm:px-3 lg:px-6 lg:pt-24 xl:px-8'>
<div className='relative z-20 flex flex-col content-between justify-center'>
<div className='relative mx-auto flex flex-col px-4 text-left'>
diff --git a/web/app/pages/Landings/SmallBusinesses.tsx b/web/app/pages/Landings/SmallBusinesses.tsx
index 1f28614e0..6db85a856 100644
--- a/web/app/pages/Landings/SmallBusinesses.tsx
+++ b/web/app/pages/Landings/SmallBusinesses.tsx
@@ -1,31 +1,20 @@
import { ArrowRightIcon } from '@heroicons/react/20/solid'
import _map from 'lodash/map'
import { useTranslation, Trans } from 'react-i18next'
-import { useSelector } from 'react-redux'
-import { Link, useLoaderData } from 'react-router'
+import { Link } from 'react-router'
import Header from '~/components/Header'
import { ComparisonTable } from '~/components/marketing/ComparisonTable'
import { DitchGoogle } from '~/components/marketing/DitchGoogle'
-import { BOOK_A_CALL_URL, DISCORD_URL, isBrowser, LIVE_DEMO_URL, TWITTER_URL } from '~/lib/constants'
-import { StateType } from '~/lib/store'
+import { BOOK_A_CALL_URL, DISCORD_URL, LIVE_DEMO_URL, TWITTER_URL } from '~/lib/constants'
import { useTheme } from '~/providers/ThemeProvider'
-import { getAccessToken } from '~/utils/accessToken'
import routesPath from '~/utils/routes'
-interface LoaderProps {
- isAuth: boolean
-}
-
const INTEGRATIONS_URL = 'https://docs.swetrix.com/integrations'
const SmallBusinesses = () => {
- const { isAuth } = useLoaderData<LoaderProps>()
const { t } = useTranslation('common')
const { theme } = useTheme()
- const accessToken = getAccessToken()
- const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)
- const authenticated = isBrowser ? (loading ? !!accessToken : reduxAuthenticated) : isAuth
return (
<main className='bg-white dark:bg-slate-900'>
@@ -59,7 +48,7 @@ const SmallBusinesses = () => {
}}
/>
</div>
- <Header authenticated={authenticated} transparent />
+ <Header transparent />
<div className='relative mx-auto min-h-[740px] pt-10 pb-5 sm:px-3 lg:px-6 lg:pt-24 xl:px-8'>
<div className='relative z-20 flex flex-col content-between justify-center'>
<div className='relative mx-auto flex flex-col px-4 text-left'>
diff --git a/web/app/pages/Landings/Startups.tsx b/web/app/pages/Landings/Startups.tsx
index f0f61779c..203c8cf8d 100644
--- a/web/app/pages/Landings/Startups.tsx
+++ b/web/app/pages/Landings/Startups.tsx
@@ -1,31 +1,20 @@
import { ArrowRightIcon } from '@heroicons/react/20/solid'
import _map from 'lodash/map'
import { useTranslation, Trans } from 'react-i18next'
-import { useSelector } from 'react-redux'
-import { Link, useLoaderData } from 'react-router'
+import { Link } from 'react-router'
import Header from '~/components/Header'
import { ComparisonTable } from '~/components/marketing/ComparisonTable'
import { DitchGoogle } from '~/components/marketing/DitchGoogle'
-import { BOOK_A_CALL_URL, DISCORD_URL, isBrowser, LIVE_DEMO_URL } from '~/lib/constants'
-import { StateType } from '~/lib/store'
+import { BOOK_A_CALL_URL, DISCORD_URL, LIVE_DEMO_URL } from '~/lib/constants'
import { useTheme } from '~/providers/ThemeProvider'
-import { getAccessToken } from '~/utils/accessToken'
import routesPath from '~/utils/routes'
-interface LoaderProps {
- isAuth: boolean
-}
-
const INTEGRATIONS_URL = 'https://docs.swetrix.com/integrations'
const Startups = () => {
- const { isAuth } = useLoaderData<LoaderProps>()
const { t } = useTranslation('common')
const { theme } = useTheme()
- const accessToken = getAccessToken()
- const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)
- const authenticated = isBrowser ? (loading ? !!accessToken : reduxAuthenticated) : isAuth
return (
<main className='bg-white dark:bg-slate-900'>
@@ -59,7 +48,7 @@ const Startups = () => {
}}
/>
</div>
- <Header authenticated={authenticated} transparent />
+ <Header transparent />
<div className='relative mx-auto min-h-[740px] pt-10 pb-5 sm:px-3 lg:px-6 lg:pt-24 xl:px-8'>
<div className='relative z-20 flex flex-col content-between justify-center'>
<div className='relative mx-auto flex flex-col px-4 text-left'>
diff --git a/web/app/pages/Organisations/OrganisationCard.tsx b/web/app/pages/Organisations/OrganisationCard.tsx
index 89cb52d1a..edd07a1b7 100644
--- a/web/app/pages/Organisations/OrganisationCard.tsx
+++ b/web/app/pages/Organisations/OrganisationCard.tsx
@@ -6,14 +6,12 @@ import _replace from 'lodash/replace'
import _size from 'lodash/size'
import React, { useState, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { Link } from 'react-router'
import { toast } from 'sonner'
import { acceptOrganisationInvitation } from '~/api'
import { DetailedOrganisation } from '~/lib/models/Organisation'
-import { authActions } from '~/lib/reducers/auth'
-import { StateType, useAppDispatch } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import { Badge, BadgeProps } from '~/ui/Badge'
import Modal from '~/ui/Modal'
import routes from '~/utils/routes'
@@ -25,13 +23,15 @@ interface OrganisationCardProps {
export const OrganisationCard = ({ organisation, reloadOrganisations }: OrganisationCardProps) => {
const { t } = useTranslation('common')
- const { user } = useSelector((state: StateType) => state.auth)
- const dispatch = useAppDispatch()
+ const { user, mergeUser } = useAuth()
const [showInviteModal, setShowInviteModal] = useState(false)
const { name, members } = organisation
- const membership = useMemo(() => _find(members, (member) => member.user.email === user.email), [members, user.email])
+ const membership = useMemo(
+ () => _find(members, (member) => member.user.email === user?.email),
+ [members, user?.email],
+ )
const badges = useMemo(() => {
const list: BadgeProps[] = []
@@ -67,16 +67,14 @@ export const OrganisationCard = ({ organisation, reloadOrganisations }: Organisa
await reloadOrganisations()
- dispatch(
- authActions.mergeUser({
- organisationMemberships: _map(user.organisationMemberships, (item) => {
- if (item.id === membership.id) {
- return { ...item, confirmed: true }
- }
- return item
- }),
+ mergeUser({
+ organisationMemberships: _map(user?.organisationMemberships, (item) => {
+ if (item.id === membership.id) {
+ return { ...item, confirmed: true }
+ }
+ return item
}),
- )
+ })
toast.success(t('apiNotifications.acceptOrganisationInvitation'))
} catch (reason: any) {
diff --git a/web/app/pages/Organisations/Organisations.tsx b/web/app/pages/Organisations/Organisations.tsx
index 7cb2d762f..3473c7d5d 100644
--- a/web/app/pages/Organisations/Organisations.tsx
+++ b/web/app/pages/Organisations/Organisations.tsx
@@ -5,7 +5,6 @@ import _map from 'lodash/map'
import _size from 'lodash/size'
import React, { useState, useEffect, useCallback } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { Link } from 'react-router'
import { ClientOnly } from 'remix-utils/client-only'
import { toast } from 'sonner'
@@ -16,7 +15,7 @@ import { withAuthentication, auth } from '~/hoc/protected'
import useDebounce from '~/hooks/useDebounce'
import { ENTRIES_PER_PAGE_DASHBOARD } from '~/lib/constants'
import { DetailedOrganisation } from '~/lib/models/Organisation'
-import { StateType } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Input from '~/ui/Input'
import Loader from '~/ui/Loader'
import Modal from '~/ui/Modal'
@@ -28,7 +27,7 @@ import { NoOrganisations } from './NoOrganisations'
import { OrganisationCard } from './OrganisationCard'
const Organisations = () => {
- const { loading: authLoading } = useSelector((state: StateType) => state.auth)
+ const { isLoading: authLoading } = useAuth()
const { t } = useTranslation('common')
const [isSearchActive, setIsSearchActive] = useState(false)
diff --git a/web/app/pages/Organisations/Settings/People.tsx b/web/app/pages/Organisations/Settings/People.tsx
index a4a62ea9f..83e79810d 100644
--- a/web/app/pages/Organisations/Settings/People.tsx
+++ b/web/app/pages/Organisations/Settings/People.tsx
@@ -7,14 +7,13 @@ import _map from 'lodash/map'
import { Trash2Icon, UserRoundPlusIcon } from 'lucide-react'
import React, { useState, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { toast } from 'sonner'
import { changeOrganisationRole, inviteOrganisationMember, removeOrganisationMember } from '~/api'
import useOnClickOutside from '~/hooks/useOnClickOutside'
import { roles, INVITATION_EXPIRES_IN } from '~/lib/constants'
import { DetailedOrganisation, Role } from '~/lib/models/Organisation'
-import { StateType } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import { Badge } from '~/ui/Badge'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
@@ -43,7 +42,7 @@ const UsersList = ({ members, onRemove }: UsersListProps) => {
t,
i18n: { language },
} = useTranslation('common')
- const { user } = useSelector((state: StateType) => state.auth)
+ const { user } = useAuth()
const [roleEditDropdownId, setRoleEditDropdownId] = useState<string | null>(null)
const openRef = useRef<HTMLUListElement>(null)
@@ -77,7 +76,7 @@ const UsersList = ({ members, onRemove }: UsersListProps) => {
<button
onClick={() => setRoleEditDropdownId((prev) => (prev === member.id ? null : member.id))}
type='button'
- disabled={member.user.email === user.email || member.role === 'owner'}
+ disabled={member.user.email === user?.email || member.role === 'owner'}
className='inline-flex items-center rounded-full border border-gray-200 bg-white py-0.5 pr-1 pl-2 text-sm leading-5 font-medium text-gray-700 hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-80 dark:border-gray-600 dark:bg-slate-800 dark:text-gray-200 dark:hover:bg-gray-600'
>
{t(`organisations.role.${member.role}.name`)}
diff --git a/web/app/pages/Organisations/Settings/Projects.tsx b/web/app/pages/Organisations/Settings/Projects.tsx
index f54b533de..6137e5370 100644
--- a/web/app/pages/Organisations/Settings/Projects.tsx
+++ b/web/app/pages/Organisations/Settings/Projects.tsx
@@ -5,7 +5,6 @@ import _map from 'lodash/map'
import _replace from 'lodash/replace'
import { useState, useEffect, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { Link } from 'react-router'
import { toast } from 'sonner'
@@ -13,7 +12,7 @@ import { removeProjectFromOrganisation, getProjectsAvailableForOrganisation, add
import useDebounce from '~/hooks/useDebounce'
import { DetailedOrganisation } from '~/lib/models/Organisation'
import { Project } from '~/lib/models/Project'
-import { StateType } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Button from '~/ui/Button'
import Loader from '~/ui/Loader'
import Modal from '~/ui/Modal'
@@ -140,7 +139,7 @@ interface ProjectListProps {
const ProjectList = ({ projects, onRemove }: ProjectListProps) => {
const { t } = useTranslation('common')
- const { user } = useSelector((state: StateType) => state.auth)
+ const { user } = useAuth()
return projects.map((project) => (
<tr key={project.id} className='dark:bg-slate-800'>
@@ -151,7 +150,7 @@ const ProjectList = ({ projects, onRemove }: ProjectListProps) => {
</td>
<td className='relative py-4 pr-2 text-sm font-medium whitespace-nowrap'>
<div className='flex items-center justify-end'>
- {project.admin.email !== user.email ? (
+ {project.admin.email !== user?.email ? (
<Tooltip
className='mr-2'
text={t('organisations.projectOwnedBy', { email: project.admin.email })}
diff --git a/web/app/pages/Organisations/Settings/index.tsx b/web/app/pages/Organisations/Settings/index.tsx
index 95380d010..87ae517e2 100644
--- a/web/app/pages/Organisations/Settings/index.tsx
+++ b/web/app/pages/Organisations/Settings/index.tsx
@@ -5,7 +5,6 @@ import _size from 'lodash/size'
import { Trash2Icon } from 'lucide-react'
import React, { useState, useEffect, useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { Link, useNavigate } from 'react-router'
import { toast } from 'sonner'
@@ -14,7 +13,7 @@ import { withAuthentication, auth } from '~/hoc/protected'
import { useRequiredParams } from '~/hooks/useRequiredParams'
import { TITLE_SUFFIX } from '~/lib/constants'
import { DetailedOrganisation } from '~/lib/models/Organisation'
-import { StateType } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
import Loader from '~/ui/Loader'
@@ -35,7 +34,7 @@ const OrganisationSettings = () => {
const { id } = useRequiredParams<{ id: string }>()
const navigate = useNavigate()
- const { loading: authLoading, user } = useSelector((state: StateType) => state.auth)
+ const { user, isLoading: authLoading } = useAuth()
const [validated, setValidated] = useState(false)
const [errors, setErrors] = useState<{
diff --git a/web/app/pages/Performance/index.tsx b/web/app/pages/Performance/index.tsx
index 1b8729d57..321b70f4d 100644
--- a/web/app/pages/Performance/index.tsx
+++ b/web/app/pages/Performance/index.tsx
@@ -2,21 +2,19 @@ import { ArrowRightIcon } from '@heroicons/react/20/solid'
import { ChevronRightIcon } from '@heroicons/react/24/solid'
import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
-import { memo, useEffect, useState } from 'react'
+import { useEffect, useState } from 'react'
import { useTranslation, Trans } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { Link } from 'react-router'
import { ClientOnly } from 'remix-utils/client-only'
import { getGeneralStats, getLastPost } from '~/api'
import Header from '~/components/Header'
import { DitchGoogle } from '~/components/marketing/DitchGoogle'
-import { PERFORMANCE_LIVE_DEMO_URL, isBrowser } from '~/lib/constants'
+import { PERFORMANCE_LIVE_DEMO_URL } from '~/lib/constants'
import { Stats } from '~/lib/models/Stats'
-import { StateType } from '~/lib/store/index'
+import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
import BackgroundSvg from '~/ui/icons/BackgroundSvg'
-import { getAccessToken } from '~/utils/accessToken'
import { nFormatterSeparated } from '~/utils/generic'
import routesPath from '~/utils/routes'
@@ -29,10 +27,6 @@ const Lines = () => (
</div>
)
-interface PerformanceProps {
- ssrAuthenticated: boolean
-}
-
export const PeopleLoveSwetrix = () => {
const { t } = useTranslation('common')
const [stats, setStats] = useState<Stats>({} as Stats)
@@ -98,13 +92,11 @@ export const PeopleLoveSwetrix = () => {
)
}
-const Performance = ({ ssrAuthenticated }: PerformanceProps) => {
+const Performance = () => {
const { t } = useTranslation('common')
const { theme } = useTheme()
- const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)
const [lastBlogPost, setLastBlogPost] = useState<Awaited<ReturnType<typeof getLastPost>> | null>(null)
- const accessToken = getAccessToken()
- const authenticated = isBrowser ? (loading ? !!accessToken : reduxAuthenticated) : ssrAuthenticated
+ const { isAuthenticated } = useAuth()
useEffect(() => {
const abortController = new AbortController()
@@ -150,7 +142,7 @@ const Performance = ({ ssrAuthenticated }: PerformanceProps) => {
}}
/>
</div>
- <Header authenticated={authenticated} transparent />
+ <Header transparent />
<div className='relative mx-auto min-h-[740px] pt-10 pb-5 sm:px-3 lg:px-6 lg:pt-24 xl:px-8'>
<div className='relative z-20 flex flex-row content-between justify-center lg:justify-start 2xl:mr-[14vw] 2xl:justify-center'>
<div className='relative px-4 text-left lg:mt-0 lg:mr-14'>
@@ -297,7 +289,7 @@ const Performance = ({ ssrAuthenticated }: PerformanceProps) => {
</div>
{/* For now let's hide Pricing for authenticated users on the main page as the Paddle script only loads on the Billing page */}
- {!authenticated ? <Pricing authenticated={false} /> : null}
+ {isAuthenticated ? null : <Pricing authenticated={false} />}
<DitchGoogle
screenshot={{
@@ -322,4 +314,4 @@ const Performance = ({ ssrAuthenticated }: PerformanceProps) => {
)
}
-export default memo(Performance)
+export default Performance
diff --git a/web/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsx b/web/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsx
index 7ecd0044d..0b047887f 100644
--- a/web/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsx
+++ b/web/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsx
@@ -10,7 +10,6 @@ import _toNumber from 'lodash/toNumber'
import _values from 'lodash/values'
import React, { useEffect, useMemo, useState } from 'react'
import { useTranslation, Trans } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { useNavigate, Link } from 'react-router'
import { toast } from 'sonner'
@@ -19,7 +18,7 @@ import { withAuthentication, auth } from '~/hoc/protected'
import { useRequiredParams } from '~/hooks/useRequiredParams'
import { PROJECT_TABS, QUERY_CONDITION, QUERY_METRIC, QUERY_TIME } from '~/lib/constants'
import { Alerts } from '~/lib/models/Alerts'
-import { StateType } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Button from '~/ui/Button'
import Checkbox from '~/ui/Checkbox'
import Input from '~/ui/Input'
@@ -35,7 +34,7 @@ interface ProjectAlertsSettingsProps {
}
const ProjectAlertsSettings = ({ isSettings }: ProjectAlertsSettingsProps) => {
- const { user, loading: authLoading } = useSelector((state: StateType) => state.auth)
+ const { user, isLoading: authLoading } = useAuth()
const navigate = useNavigate()
const { id, pid } = useRequiredParams<{ id: string; pid: string }>()
diff --git a/web/app/pages/Project/Alerts/View/ProjectAlertsView.tsx b/web/app/pages/Project/Alerts/View/ProjectAlertsView.tsx
index 83c6162cc..db11ecc20 100644
--- a/web/app/pages/Project/Alerts/View/ProjectAlertsView.tsx
+++ b/web/app/pages/Project/Alerts/View/ProjectAlertsView.tsx
@@ -15,23 +15,21 @@ import _values from 'lodash/values'
import { Trash2Icon, BellRingIcon } from 'lucide-react'
import { useMemo, useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { useNavigate, Link } from 'react-router'
import { toast } from 'sonner'
import { deleteAlert as deleteAlertApi, getProjectAlerts } from '~/api'
import { QUERY_METRIC, PLAN_LIMITS, DEFAULT_ALERTS_TAKE } from '~/lib/constants'
import { Alerts } from '~/lib/models/Alerts'
-import { StateType } from '~/lib/store'
import PaidFeature from '~/modals/PaidFeature'
+import { useAuth } from '~/providers/AuthProvider'
+import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import Button from '~/ui/Button'
import Loader from '~/ui/Loader'
import Modal from '~/ui/Modal'
import Pagination from '~/ui/Pagination'
import routes from '~/utils/routes'
-import { useCurrentProject } from '../../../../providers/CurrentProjectProvider'
-
const Separator = ({ className }: { className?: string }) => (
<svg viewBox='0 0 2 2' className={cx('h-0.5 w-0.5 flex-none fill-gray-400', className)}>
<circle cx={1} cy={1} r={1} />
@@ -184,7 +182,7 @@ const AddAlert = ({ handleNewAlert, isLimitReached }: AddAlertProps) => {
const ProjectAlerts = () => {
const { id } = useCurrentProject()
const { t } = useTranslation()
- const { user, authenticated } = useSelector((state: StateType) => state.auth)
+ const { user, isAuthenticated } = useAuth()
const [isPaidFeatureOpened, setIsPaidFeatureOpened] = useState(false)
const [isLoading, setIsLoading] = useState<boolean | null>(null)
@@ -198,8 +196,8 @@ const ProjectAlerts = () => {
const navigate = useNavigate()
- const limits = PLAN_LIMITS[user?.planCode] || PLAN_LIMITS.trial
- const isLimitReached = authenticated && total >= limits?.maxAlerts
+ const limits = PLAN_LIMITS[user?.planCode || 'trial']
+ const isLimitReached = isAuthenticated && total >= limits?.maxAlerts
const loadAlerts = async (take: number, skip: number) => {
if (isLoading) {
diff --git a/web/app/pages/Project/New/index.tsx b/web/app/pages/Project/New/index.tsx
index a73f68f99..b7e63ae4b 100644
--- a/web/app/pages/Project/New/index.tsx
+++ b/web/app/pages/Project/New/index.tsx
@@ -3,7 +3,6 @@ import _keys from 'lodash/keys'
import _size from 'lodash/size'
import React, { useState, useEffect, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { Link, useNavigate } from 'react-router'
import { toast } from 'sonner'
@@ -11,7 +10,7 @@ import { createProject } from '~/api'
import { withAuthentication, auth } from '~/hoc/protected'
import { isSelfhosted, TITLE_SUFFIX } from '~/lib/constants'
import { Project } from '~/lib/models/Project'
-import { useAppDispatch, StateType } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
import Loader from '~/ui/Loader'
@@ -24,8 +23,7 @@ const MAX_NAME_LENGTH = 50
const DEFAULT_PROJECT_NAME = 'Untitled Project'
const NewProject = () => {
- const dispatch = useAppDispatch()
- const { user, loading } = useSelector((state: StateType) => state.auth)
+ const { user, isLoading } = useAuth()
const { t } = useTranslation('common')
const navigate = useNavigate()
@@ -46,15 +44,15 @@ const NewProject = () => {
id: undefined,
name: t('common.notSet'),
},
- ...(user.organisationMemberships || [])
+ ...(user?.organisationMemberships || [])
.filter((om) => om.confirmed && (om.role === 'admin' || om.role === 'owner'))
.map((om) => om.organisation),
],
- [user.organisationMemberships, t],
+ [user?.organisationMemberships, t],
)
useEffect(() => {
- if (loading) {
+ if (isLoading || !user) {
return
}
@@ -62,7 +60,7 @@ const NewProject = () => {
toast.error(t('project.settings.verify'))
navigate(routes.dashboard)
}
- }, [user, navigate, dispatch, t, loading])
+ }, [user, navigate, t, isLoading])
const onSubmit = async (data: Partial<Project>) => {
if (!projectSaving) {
@@ -130,7 +128,7 @@ const NewProject = () => {
document.title = `${t('project.settings.create')} ${TITLE_SUFFIX}`
}, [t])
- if (loading) {
+ if (isLoading) {
return (
<div className='min-h-min-footer flex flex-col bg-gray-50 px-4 py-6 sm:px-6 lg:px-8 dark:bg-slate-900'>
<Loader />
diff --git a/web/app/pages/Project/ProjectProtectedPassword/index.tsx b/web/app/pages/Project/ProjectProtectedPassword/index.tsx
index 8583c1339..d207bb675 100644
--- a/web/app/pages/Project/ProjectProtectedPassword/index.tsx
+++ b/web/app/pages/Project/ProjectProtectedPassword/index.tsx
@@ -25,10 +25,9 @@ const MAX_PASSWORD_LENGTH = 80
interface ProjectProtectedPasswordProps {
embedded: boolean
- isAuth: boolean
}
-const ProjectProtectedPassword = ({ embedded, isAuth }: ProjectProtectedPasswordProps) => {
+const ProjectProtectedPassword = ({ embedded }: ProjectProtectedPasswordProps) => {
const { theme } = useTheme()
const { t } = useTranslation('common')
const [form, setForm] = useState<ProjectProtectedPasswordForm>({
@@ -111,7 +110,7 @@ const ProjectProtectedPassword = ({ embedded, isAuth }: ProjectProtectedPassword
return (
<>
- {!embedded ? <Header authenticated={isAuth} /> : null}
+ {!embedded ? <Header /> : null}
<div className='min-h-page flex flex-col bg-gray-50 px-4 py-6 sm:px-6 lg:px-8 dark:bg-slate-900'>
<form className='mx-auto w-full max-w-7xl' onSubmit={handleSubmit}>
<h2 className='mt-2 text-3xl font-bold text-gray-900 dark:text-gray-50'>{t('titles.passwordProtected')}</h2>
@@ -142,7 +141,7 @@ const ProjectProtectedPassword = ({ embedded, isAuth }: ProjectProtectedPassword
</div>
</form>
</div>
- {!embedded ? <Footer authenticated={isAuth} /> : null}
+ {!embedded ? <Footer /> : null}
</>
)
}
diff --git a/web/app/pages/Project/Settings/People/People.tsx b/web/app/pages/Project/Settings/People/People.tsx
index 76be6ec83..9c3f1a245 100644
--- a/web/app/pages/Project/Settings/People/People.tsx
+++ b/web/app/pages/Project/Settings/People/People.tsx
@@ -7,7 +7,6 @@ import _map from 'lodash/map'
import { Trash2Icon, UserRoundPlusIcon } from 'lucide-react'
import React, { useState, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { toast } from 'sonner'
import { deleteShareProjectUsers, shareProject, changeShareRole } from '~/api'
@@ -15,8 +14,8 @@ import useOnClickOutside from '~/hooks/useOnClickOutside'
import { roles, INVITATION_EXPIRES_IN } from '~/lib/constants'
import { Role } from '~/lib/models/Organisation'
import { Project, ShareOwnerProject } from '~/lib/models/Project'
-import { StateType } from '~/lib/store'
import PaidFeature from '~/modals/PaidFeature'
+import { useAuth } from '~/providers/AuthProvider'
import { Badge } from '~/ui/Badge'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
@@ -144,7 +143,7 @@ interface PeopleProps {
}
const People = ({ project }: PeopleProps) => {
- const { user: currentUser } = useSelector((state: StateType) => state.auth)
+ const { user: currentUser } = useAuth()
const [showModal, setShowModal] = useState(false)
const [isPaidFeatureOpened, setIsPaidFeatureOpened] = useState(false)
diff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsx
index af8ea6641..c3722a42a 100644
--- a/web/app/pages/Project/Settings/ProjectSettings.tsx
+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx
@@ -15,7 +15,6 @@ import _toUpper from 'lodash/toUpper'
import { ArrowLeftRight, RotateCcw, Trash2Icon } from 'lucide-react'
import React, { useState, useEffect, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { useLoaderData, useNavigate, Link } from 'react-router'
import { toast } from 'sonner'
@@ -34,7 +33,7 @@ import { withAuthentication, auth } from '~/hoc/protected'
import { useRequiredParams } from '~/hooks/useRequiredParams'
import { isSelfhosted, TITLE_SUFFIX, FILTERS_PANELS_ORDER, isBrowser } from '~/lib/constants'
import { Project } from '~/lib/models/Project'
-import { StateType } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Button from '~/ui/Button'
import Checkbox from '~/ui/Checkbox'
import Dropdown from '~/ui/Dropdown'
@@ -253,7 +252,7 @@ interface Form extends Partial<Project> {
const DEFAULT_PROJECT_NAME = 'Untitled Project'
const ProjectSettings = () => {
- const { user, loading: authLoading } = useSelector((state: StateType) => state.auth)
+ const { user, isLoading: authLoading } = useAuth()
const { t } = useTranslation('common')
const { id } = useRequiredParams<{ id: string }>()
@@ -315,11 +314,11 @@ const ProjectSettings = () => {
id: undefined,
name: t('common.notSet'),
},
- ...(user.organisationMemberships || [])
+ ...(user?.organisationMemberships || [])
.filter((om) => om.confirmed && (om.role === 'admin' || om.role === 'owner'))
.map((om) => om.organisation),
],
- [user.organisationMemberships, t],
+ [user?.organisationMemberships, t],
)
const assignOrganisation = async (organisationId?: string) => {
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index f56cc215f..614206a74 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -50,7 +50,6 @@ import React, {
} from 'react'
import { useHotkeys } from 'react-hotkeys-hook'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { useNavigate, Link, useSearchParams, useLoaderData } from 'react-router'
import { ClientOnly } from 'remix-utils/client-only'
import { toast } from 'sonner'
@@ -101,7 +100,6 @@ import {
PERIOD_PAIRS_COMPARE,
FILTERS_PERIOD_PAIRS,
LS_IS_ACTIVE_COMPARE_KEY,
- isBrowser,
TITLE_SUFFIX,
KEY_FOR_ALL_TIME,
MARKETPLACE_URL,
@@ -115,9 +113,9 @@ import {
} from '~/lib/constants'
import { CountryEntry } from '~/lib/models/Entry'
import { Funnel, AnalyticsFunnel, OverallObject, OverallPerformanceObject } from '~/lib/models/Project'
-import { StateType } from '~/lib/store'
import NewFunnel from '~/modals/NewFunnel'
import ViewProjectHotkeys from '~/modals/ViewProjectHotkeys'
+import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
import Checkbox from '~/ui/Checkbox'
import Dropdown from '~/ui/Dropdown'
@@ -249,26 +247,18 @@ export const useViewProjectContext = () => {
}
const ViewProject = () => {
- const { id, project, preferences, updatePreferences } = useCurrentProject()
+ const { id, project, preferences, updatePreferences, extensions } = useCurrentProject()
const projectPassword = useProjectPassword(id)
- const {
- embedded,
- isAuth: ssrAuthenticated,
- tabs: projectQueryTabs,
- } = useLoaderData<{
+ const { embedded, tabs: projectQueryTabs } = useLoaderData<{
embedded: boolean
- isAuth: boolean
tabs: string[]
}>()
- const { loading: authLoading, authenticated: csrAuthenticated, user } = useSelector((state: StateType) => state.auth)
-
const { theme } = useTheme()
- const { extensions } = useSelector((state: StateType) => state.auth)
+ const { isAuthenticated, user, isLoading: authLoading } = useAuth()
- const authenticated = isBrowser ? (authLoading ? ssrAuthenticated : csrAuthenticated) : ssrAuthenticated
const { timezone = DEFAULT_TIMEZONE } = user || {}
const {
@@ -524,7 +514,7 @@ const ViewProject = () => {
const [isPanelsDataEmptyPerf, setIsPanelsDataEmptyPerf] = useState(false)
const [panelsDataPerf, setPanelsDataPerf] = useState<any>({})
- const timeFormat = useMemo<'12-hour' | '24-hour'>(() => user.timeFormat || TimeFormat['12-hour'], [user])
+ const timeFormat = useMemo<'12-hour' | '24-hour'>(() => user?.timeFormat || TimeFormat['12-hour'], [user])
const [ref, size] = useSize()
const rotateXAxis = useMemo(() => size.width > 0 && size.width < 500, [size])
const customEventsChartData = useMemo(
@@ -2808,7 +2798,7 @@ const ViewProject = () => {
if (authLoading || !project) {
return (
<>
- {!embedded ? <Header authenticated={authenticated} /> : null}
+ {!embedded ? <Header /> : null}
<div
className={cx('min-h-min-footer bg-gray-50 dark:bg-slate-900', {
'min-h-min-footer': !embedded,
@@ -2817,7 +2807,7 @@ const ViewProject = () => {
>
<Loader />
</div>
- {!embedded ? <Footer authenticated={authenticated} /> : null}
+ {!embedded ? <Footer /> : null}
</>
)
}
@@ -2825,7 +2815,7 @@ const ViewProject = () => {
if (project.isLocked) {
return (
<>
- {!embedded ? <Header authenticated={authenticated} /> : null}
+ {!embedded ? <Header /> : null}
<div
className={cx('mx-auto w-full max-w-[1584px] bg-gray-50 px-2 py-6 sm:px-4 lg:px-8 dark:bg-slate-900', {
'min-h-min-footer': !embedded,
@@ -2836,9 +2826,9 @@ const ViewProject = () => {
<h2 className='mt-2 text-center font-mono text-xl font-bold break-words break-all text-gray-900 sm:text-left dark:text-gray-50'>
{project.name}
</h2>
- <LockedDashboard user={user} project={project} />
+ <LockedDashboard project={project} />
</div>
- {!embedded ? <Footer authenticated={authenticated} /> : null}
+ {!embedded ? <Footer /> : null}
</>
)
}
@@ -2846,7 +2836,7 @@ const ViewProject = () => {
if (!project.isDataExists && activeTab !== PROJECT_TABS.errors && !analyticsLoading) {
return (
<>
- {!embedded ? <Header authenticated={authenticated} /> : null}
+ {!embedded ? <Header /> : null}
<div
className={cx('mx-auto w-full max-w-[1584px] bg-gray-50 px-2 py-6 sm:px-4 lg:px-8 dark:bg-slate-900', {
'min-h-min-footer': !embedded,
@@ -2859,7 +2849,7 @@ const ViewProject = () => {
</h2>
<WaitingForAnEvent project={project} />
</div>
- {!embedded ? <Footer authenticated={authenticated} /> : null}
+ {!embedded ? <Footer /> : null}
</>
)
}
@@ -2871,7 +2861,7 @@ const ViewProject = () => {
) {
return (
<>
- {!embedded ? <Header authenticated={authenticated} /> : null}
+ {!embedded ? <Header /> : null}
<div
className={cx('mx-auto w-full max-w-[1584px] bg-gray-50 px-2 py-6 sm:px-4 lg:px-8 dark:bg-slate-900', {
'min-h-min-footer': !embedded,
@@ -2884,7 +2874,7 @@ const ViewProject = () => {
</h2>
<WaitingForAnError />
</div>
- {!embedded ? <Footer authenticated={authenticated} /> : null}
+ {!embedded ? <Footer /> : null}
</>
)
}
@@ -2931,7 +2921,7 @@ const ViewProject = () => {
}}
>
<>
- {!embedded ? <Header authenticated={authenticated} /> : null}
+ {!embedded ? <Header /> : null}
<EventsRunningOutBanner />
<div
ref={ref}
@@ -3509,7 +3499,7 @@ const ViewProject = () => {
) : null}
</>
) : null}
- {activeTab === PROJECT_TABS.alerts && (project.role !== 'owner' || !authenticated) ? (
+ {activeTab === PROJECT_TABS.alerts && (project.role !== 'owner' || !isAuthenticated) ? (
<div className='mt-5 rounded-xl bg-gray-700 p-5'>
<div className='flex items-center text-gray-50'>
<BellRingIcon className='mr-2 h-8 w-8' strokeWidth={1.5} />
@@ -3542,7 +3532,7 @@ const ViewProject = () => {
funnels={project.funnels}
deleteFunnel={onFunnelDelete}
loading={funnelActionLoading}
- authenticated={authenticated}
+ authenticated={isAuthenticated}
allowedToManage={allowedToManage}
/>
) : null}
@@ -3555,7 +3545,7 @@ const ViewProject = () => {
<p className='mt-2 font-mono text-sm whitespace-pre-wrap text-gray-100'>
{t('dashboard.funnelsDesc')}
</p>
- {authenticated ? (
+ {isAuthenticated ? (
<button
type='button'
onClick={() => setIsNewFunnelOpened(true)}
@@ -3948,7 +3938,7 @@ const ViewProject = () => {
{!errorLoading && _isEmpty(activeError) ? <NoErrorDetails /> : null}
</>
) : null}
- {activeTab === PROJECT_TABS.alerts && project.role === 'owner' && authenticated ? (
+ {activeTab === PROJECT_TABS.alerts && project.role === 'owner' && isAuthenticated ? (
<ProjectAlertsView />
) : null}
{analyticsLoading && (activeTab === PROJECT_TABS.traffic || activeTab === PROJECT_TABS.performance) ? (
@@ -4564,7 +4554,7 @@ const ViewProject = () => {
pid={id}
tnMapping={tnMapping}
/>
- {!embedded ? <Footer authenticated={authenticated} showDBIPMessage /> : null}
+ {!embedded ? <Footer showDBIPMessage /> : null}
</>
</ViewProjectContext.Provider>
)}
diff --git a/web/app/pages/Project/View/components/LockedDashboard.tsx b/web/app/pages/Project/View/components/LockedDashboard.tsx
index 890037b94..99570a678 100644
--- a/web/app/pages/Project/View/components/LockedDashboard.tsx
+++ b/web/app/pages/Project/View/components/LockedDashboard.tsx
@@ -4,15 +4,16 @@ import { useTranslation } from 'react-i18next'
import { Link } from 'react-router'
import { ProjectForShared } from '~/lib/models/SharedProject'
-import { User, DashboardBlockReason } from '~/lib/models/User'
+import { DashboardBlockReason } from '~/lib/models/User'
+import { useAuth } from '~/providers/AuthProvider'
import routes from '~/utils/routes'
interface LockedDashboardProps {
- user?: User
project: ProjectForShared
}
-const LockedDashboard = ({ user, project }: LockedDashboardProps) => {
+const LockedDashboard = ({ project }: LockedDashboardProps) => {
+ const { user } = useAuth()
const { t } = useTranslation('common')
const message = useMemo(() => {
diff --git a/web/app/pages/ReferralPage/index.tsx b/web/app/pages/ReferralPage/index.tsx
index be92c5c3a..877216f0d 100644
--- a/web/app/pages/ReferralPage/index.tsx
+++ b/web/app/pages/ReferralPage/index.tsx
@@ -48,7 +48,7 @@ const ReferralPage = () => {
}}
/>
</div>
- <Header authenticated={false} refPage transparent />
+ <Header refPage transparent />
<div className='relative mx-auto min-h-[740px] pt-10 pb-5 sm:px-3 lg:px-6 lg:pt-24 xl:px-8'>
<div className='relative z-20 flex flex-row content-between justify-center lg:justify-start 2xl:mr-[14vw] 2xl:justify-center'>
<div className='relative px-4 text-left lg:mt-0 lg:mr-14'>
diff --git a/web/app/pages/Unsubscribe/index.tsx b/web/app/pages/Unsubscribe/index.tsx
index d9f54fa46..dadc0cd2e 100644
--- a/web/app/pages/Unsubscribe/index.tsx
+++ b/web/app/pages/Unsubscribe/index.tsx
@@ -2,11 +2,10 @@ import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/solid'
import _isString from 'lodash/isString'
import { useState, useEffect, memo } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { useParams, Link } from 'react-router'
import { unsubscribeFromEmailReports, unsubscribeFromEmailReports3rdParty } from '~/api'
-import { StateType } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Loader from '~/ui/Loader'
import routes from '~/utils/routes'
@@ -17,7 +16,7 @@ interface UnsubscribeProps {
const Unsubscribe = ({ type }: UnsubscribeProps) => {
const { t } = useTranslation('common')
const { token } = useParams()
- const { authenticated } = useSelector((state: StateType) => state.auth)
+ const { isAuthenticated } = useAuth()
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
@@ -78,7 +77,7 @@ const Unsubscribe = ({ type }: UnsubscribeProps) => {
</h1>
</div>
<div className='mt-8 flex space-x-3 font-mono sm:border-l sm:border-transparent sm:pl-6'>
- {authenticated ? (
+ {isAuthenticated ? (
<Link
to={routes.dashboard}
className='inline-flex items-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:outline-hidden'
@@ -119,7 +118,7 @@ const Unsubscribe = ({ type }: UnsubscribeProps) => {
</h1>
</div>
<div className='mt-8 flex space-x-3 font-mono sm:border-l sm:border-transparent sm:pl-6'>
- {authenticated ? (
+ {isAuthenticated ? (
<Link
to={routes.dashboard}
className='inline-flex items-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:outline-hidden'
diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsx
index 87e79db36..4cdc33dcd 100644
--- a/web/app/pages/UserSettings/UserSettings.tsx
+++ b/web/app/pages/UserSettings/UserSettings.tsx
@@ -18,7 +18,6 @@ import _size from 'lodash/size'
import { DownloadIcon, MessageSquareTextIcon, MonitorIcon, UserRoundIcon } from 'lucide-react'
import React, { useState, useEffect, memo, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { useNavigate } from 'react-router'
import { ClientOnly } from 'remix-utils/client-only'
import { toast } from 'sonner'
@@ -44,9 +43,8 @@ import {
isSelfhosted,
} from '~/lib/constants'
import { User } from '~/lib/models/User'
-import { authActions } from '~/lib/reducers/auth'
-import { StateType, useAppDispatch } from '~/lib/store'
import PaidFeature from '~/modals/PaidFeature'
+import { useAuth } from '~/providers/AuthProvider'
import Button from '~/ui/Button'
import Checkbox from '~/ui/Checkbox'
import Input from '~/ui/Input'
@@ -55,11 +53,8 @@ import Modal from '~/ui/Modal'
import Select from '~/ui/Select'
import Textarea from '~/ui/Textarea'
import TimezonePicker from '~/ui/TimezonePicker'
-import { removeAccessToken } from '~/utils/accessToken'
import { trackCustom } from '~/utils/analytics'
-import { logout } from '~/utils/auth'
import { getCookie, setCookie } from '~/utils/cookie'
-import { removeRefreshToken } from '~/utils/refreshToken'
import routes from '~/utils/routes'
import { isValidEmail, isValidPassword, MIN_PASSWORD_CHARS } from '~/utils/validator'
@@ -130,23 +125,22 @@ interface Form extends Partial<User> {
}
const UserSettings = () => {
- const { user, loading } = useSelector((state: StateType) => state.auth)
- const dispatch = useAppDispatch()
+ const { user, isLoading, logout, setUser, mergeUser } = useAuth()
const navigate = useNavigate()
const { t } = useTranslation('common')
const [activeTab, setActiveTab] = useState(TAB_MAPPING.ACCOUNT)
const [form, setForm] = useState<Form>({
- email: user.email || '',
+ email: user?.email || '',
password: '',
repeat: '',
- timeFormat: user.timeFormat || TimeFormat['12-hour'],
+ timeFormat: user?.timeFormat || TimeFormat['12-hour'],
})
const [showPasswordFields, setShowPasswordFields] = useState(false)
- const [timezone, setTimezone] = useState(user.timezone || DEFAULT_TIMEZONE)
+ const [timezone, setTimezone] = useState(user?.timezone || DEFAULT_TIMEZONE)
const [isPaidFeatureOpened, setIsPaidFeatureOpened] = useState(false)
const [isPasswordChangeModalOpened, setIsPasswordChangeModalOpened] = useState(false)
- const [reportFrequency, setReportFrequency] = useState(user.reportFrequency)
+ const [reportFrequency, setReportFrequency] = useState(user?.reportFrequency)
const [formPresetted, setFormPresetted] = useState(false)
const [validated, setValidated] = useState(false)
const [errors, setErrors] = useState<Record<string, string>>({})
@@ -197,43 +191,33 @@ const UserSettings = () => {
try {
const result = await changeUserDetails(data)
- dispatch(authActions.setUser(result))
+ setUser(result)
toast.success(t('profileSettings.updated'))
} catch (reason: any) {
toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
} finally {
callback(true)
- dispatch(authActions.finishLoading())
}
}
- const logoutLocal = () => {
- dispatch(authActions.logout())
- removeRefreshToken()
- removeAccessToken()
- }
-
- const logoutAll = () => {
- dispatch(authActions.logout())
- logout(true)
- }
-
useEffect(() => {
validate()
}, [form]) // eslint-disable-line
useEffect(() => {
- if (!loading && !formPresetted) {
- setForm((prev) => ({
- ...prev,
- email: user.email || '',
- timeFormat: user.timeFormat || TimeFormat['12-hour'],
- }))
- setTimezone(user.timezone || DEFAULT_TIMEZONE)
- setReportFrequency(user.reportFrequency)
- setFormPresetted(true)
+ if (isLoading || !user || formPresetted) {
+ return
}
- }, [loading, user, formPresetted])
+
+ setForm((prev) => ({
+ ...prev,
+ email: user.email || '',
+ timeFormat: user.timeFormat || TimeFormat['12-hour'],
+ }))
+ setTimezone(user.timezone || DEFAULT_TIMEZONE)
+ setReportFrequency(user.reportFrequency)
+ setFormPresetted(true)
+ }, [isLoading, user, formPresetted])
const handleInput = (event: React.ChangeEvent<HTMLInputElement>) => {
const { target } = event
@@ -287,7 +271,7 @@ const UserSettings = () => {
try {
await setShowLiveVisitorsInTitle(checked)
- dispatch(authActions.mergeUser({ showLiveVisitorsInTitle: checked }))
+ mergeUser({ showLiveVisitorsInTitle: checked })
toast.success(t('profileSettings.updated'))
} catch (reason: any) {
toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
@@ -305,7 +289,7 @@ const UserSettings = () => {
try {
await receiveLoginNotification(checked)
- dispatch(authActions.mergeUser({ receiveLoginNotifications: checked }))
+ mergeUser({ receiveLoginNotifications: checked })
toast.success(t('profileSettings.updated'))
} catch {
toast.error(t('apiNotifications.somethingWentWrong'))
@@ -342,7 +326,7 @@ const UserSettings = () => {
const onAccountDelete = async () => {
try {
await deleteUser(deletionFeedback)
- dispatch(authActions.logout())
+ logout(true)
toast.success(t('apiNotifications.accountDeleted'))
trackCustom('ACCOUNT_DELETED', {
reason_stated: deletionFeedback ? 'true' : 'false',
@@ -350,12 +334,10 @@ const UserSettings = () => {
navigate(routes.main)
} catch (reason: any) {
toast.error(t(`apiNotifications.${reason}`, 'apiNotifications.somethingWentWrong'))
- } finally {
- dispatch(authActions.finishLoading())
}
}
- const onExport = async (exportedAt: string) => {
+ const onExport = async (exportedAt: string | null) => {
try {
if (
getCookie(GDPR_REQUEST) ||
@@ -401,7 +383,7 @@ const UserSettings = () => {
const onApiKeyGenerate = async () => {
try {
const { apiKey } = await generateApiKey()
- dispatch(authActions.mergeUser({ apiKey }))
+ mergeUser({ apiKey })
} catch (reason: any) {
toast.error(reason)
}
@@ -410,7 +392,7 @@ const UserSettings = () => {
const onApiKeyDelete = async () => {
try {
await deleteApiKey()
- dispatch(authActions.mergeUser({ apiKey: null }))
+ mergeUser({ apiKey: null })
} catch (reason: any) {
toast.error(reason)
}
@@ -497,7 +479,7 @@ const UserSettings = () => {
</div>
<ClientOnly fallback={<Loader />}>
{() => {
- if (loading) {
+ if (isLoading) {
return <Loader />
}
@@ -526,7 +508,7 @@ const UserSettings = () => {
<h3 className='mt-2 flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'>
{t('profileSettings.apiKey')}
</h3>
- {user.apiKey ? (
+ {user?.apiKey ? (
<>
<p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
{t('profileSettings.apiKeyWarning')}
@@ -595,7 +577,7 @@ const UserSettings = () => {
<h3 className='mt-2 flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'>
{t('profileSettings.apiKey')}
</h3>
- {user.apiKey ? (
+ {user?.apiKey ? (
<>
<p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
{t('profileSettings.apiKeyWarning')}
@@ -615,7 +597,7 @@ const UserSettings = () => {
{t('profileSettings.noApiKey')}
</p>
)}
- {user.apiKey ? (
+ {user?.apiKey ? (
<Button className='mt-4' onClick={() => setShowAPIDeleteModal(true)} danger large>
{t('profileSettings.deleteApiKeyBtn')}
</Button>
@@ -648,7 +630,7 @@ const UserSettings = () => {
{t('profileSettings.shared')}
</h3>
<div>
- {!_isEmpty(user.sharedProjects) ? (
+ {!_isEmpty(user?.sharedProjects) ? (
<div className='mt-3 flex flex-col font-mono'>
<div className='-mx-4 -my-2 overflow-x-auto sm:-mx-6 lg:-mx-8'>
<div className='inline-block min-w-full py-2 align-middle md:px-6 lg:px-8'>
@@ -678,7 +660,7 @@ const UserSettings = () => {
</tr>
</thead>
<tbody className='divide-y divide-gray-300 dark:divide-gray-600'>
- {_map(user.sharedProjects, (item) => (
+ {_map(user?.sharedProjects, (item) => (
<ProjectList key={item.id} item={item} />
))}
</tbody>
@@ -698,7 +680,7 @@ const UserSettings = () => {
{t('profileSettings.organisations')}
</h3>
<div>
- {!_isEmpty(user.organisationMemberships) ? (
+ {!_isEmpty(user?.organisationMemberships) ? (
<div className='mt-3 flex flex-col font-mono'>
<div className='-mx-4 -my-2 overflow-x-auto sm:-mx-6 lg:-mx-8'>
<div className='inline-block min-w-full py-2 align-middle md:px-6 lg:px-8'>
@@ -728,7 +710,7 @@ const UserSettings = () => {
</tr>
</thead>
<tbody className='divide-y divide-gray-300 dark:divide-gray-600'>
- {_map(user.organisationMemberships, (membership) => (
+ {_map(user?.organisationMemberships, (membership) => (
<Organisations key={membership.id} membership={membership} />
))}
</tbody>
@@ -743,7 +725,7 @@ const UserSettings = () => {
</div>
<hr className='mt-5 border-gray-200 dark:border-gray-600' />
- {!user.isActive ? (
+ {!user?.isActive ? (
<div
className='mt-4 flex max-w-max cursor-pointer pl-0 text-blue-600 underline hover:text-indigo-800 dark:hover:text-indigo-600'
onClick={() => onEmailConfirm(setError)}
@@ -760,7 +742,13 @@ const UserSettings = () => {
</>
</Button>
<div className='flex flex-wrap justify-center gap-2'>
- <Button onClick={logoutAll} semiSmall semiDanger>
+ <Button
+ onClick={() => {
+ logout(true)
+ }}
+ semiSmall
+ semiDanger
+ >
<>
{/* We need this div for the button to match the height of the button after it */}
<div className='h-5' />
@@ -828,7 +816,7 @@ const UserSettings = () => {
{t('profileSettings.uiSettings')}
</h3>
<Checkbox
- checked={user.showLiveVisitorsInTitle}
+ checked={user?.showLiveVisitorsInTitle}
onChange={handleShowLiveVisitorsSave}
disabled={settingUpdating}
name='active'
@@ -879,9 +867,9 @@ const UserSettings = () => {
{t('profileSettings.integrations')}
</h3>
<Integrations handleIntegrationSave={handleIntegrationSave} />
- {user.isTelegramChatIdConfirmed ? (
+ {user?.isTelegramChatIdConfirmed ? (
<Checkbox
- checked={user.receiveLoginNotifications}
+ checked={user?.receiveLoginNotifications}
onChange={handleReceiveLoginNotifications}
disabled={settingUpdating}
name='receiveLoginNotifications'
@@ -921,7 +909,7 @@ const UserSettings = () => {
onClose={() => setShowExportModal(false)}
onSubmit={() => {
setShowExportModal(false)
- onExport(user.exportedAt)
+ onExport(user?.exportedAt || null)
}}
submitText={t('common.continue')}
closeText={t('common.close')}
@@ -991,7 +979,7 @@ const UserSettings = () => {
handleSubmit(null, true, (isSuccess: boolean) => {
// password has been changed, let's log out the user as all the sessions are now invalid
if (isSuccess) {
- logoutLocal()
+ logout()
}
})
}}
diff --git a/web/app/pages/UserSettings/components/Integrations.tsx b/web/app/pages/UserSettings/components/Integrations.tsx
index a494df5e6..22966389b 100644
--- a/web/app/pages/UserSettings/components/Integrations.tsx
+++ b/web/app/pages/UserSettings/components/Integrations.tsx
@@ -4,13 +4,11 @@ import _isString from 'lodash/isString'
import _map from 'lodash/map'
import React, { useState, memo } from 'react'
import { useTranslation, Trans } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { toast } from 'sonner'
import { removeTgIntegration } from '~/api'
import { User } from '~/lib/models/User'
-import { authActions } from '~/lib/reducers/auth'
-import { StateType, useAppDispatch } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Button from '~/ui/Button'
import Discord from '~/ui/icons/Discord'
import Slack from '~/ui/icons/Slack'
@@ -56,8 +54,7 @@ interface IntegrationsProps {
}
const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
- const dispatch = useAppDispatch()
- const { user } = useSelector((state: StateType) => state.auth)
+ const { user, mergeUser } = useAuth()
const { t } = useTranslation('common')
const available = getAvailableIntegrations(t)
@@ -126,6 +123,10 @@ const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
}
const getIntegrationStatus = (key: string) => {
+ if (!user) {
+ return {}
+ }
+
if (key === 'telegram') {
return {
connected: user.telegramChatId,
@@ -154,7 +155,7 @@ const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
}
const removeIntegration = async (key: string) => {
- if (isRemovalLoading) {
+ if (isRemovalLoading || !user) {
return
}
@@ -167,12 +168,10 @@ const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
} else {
throw new Error('No chat ID')
}
- dispatch(
- authActions.mergeUser({
- isTelegramChatIdConfirmed: false,
- telegramChatId: null,
- }),
- )
+ mergeUser({
+ isTelegramChatIdConfirmed: false,
+ telegramChatId: null,
+ })
} catch (reason) {
if (_isString(reason)) {
toast.error(reason)
@@ -195,11 +194,9 @@ const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
toast.error(t('apiNotifications.integrationRemovalError'))
}
- dispatch(
- authActions.mergeUser({
- slackWebhookUrl: null,
- }),
- )
+ mergeUser({
+ slackWebhookUrl: null,
+ })
setIsRemovalLoading(false)
},
)
@@ -215,11 +212,9 @@ const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
toast.error(t('apiNotifications.integrationRemovalError'))
}
- dispatch(
- authActions.mergeUser({
- discordWebhookUrl: null,
- }),
- )
+ mergeUser({
+ discordWebhookUrl: null,
+ })
setIsRemovalLoading(false)
},
)
diff --git a/web/app/pages/UserSettings/components/Organisations.tsx b/web/app/pages/UserSettings/components/Organisations.tsx
index 88b4032fd..a6fd0f80e 100644
--- a/web/app/pages/UserSettings/components/Organisations.tsx
+++ b/web/app/pages/UserSettings/components/Organisations.tsx
@@ -4,13 +4,11 @@ import _filter from 'lodash/filter'
import _map from 'lodash/map'
import { memo, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { toast } from 'sonner'
import { rejectOrganisationInvitation, acceptOrganisationInvitation } from '~/api'
import { OrganisationMembership } from '~/lib/models/Organisation'
-import { authActions } from '~/lib/reducers/auth'
-import { StateType, useAppDispatch } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Button from '~/ui/Button'
import Modal from '~/ui/Modal'
@@ -19,8 +17,7 @@ interface OrganisationsProps {
}
const Organisations = ({ membership }: OrganisationsProps) => {
- const { user } = useSelector((state: StateType) => state.auth)
- const dispatch = useAppDispatch()
+ const { user, mergeUser } = useAuth()
const {
t,
i18n: { language },
@@ -33,14 +30,12 @@ const Organisations = ({ membership }: OrganisationsProps) => {
try {
await rejectOrganisationInvitation(membership.id)
- dispatch(
- authActions.mergeUser({
- organisationMemberships: _filter(
- user.organisationMemberships,
- (userMembership) => userMembership.id !== membership.id,
- ),
- }),
- )
+ mergeUser({
+ organisationMemberships: _filter(
+ user?.organisationMemberships,
+ (userMembership) => userMembership.id !== membership.id,
+ ),
+ })
toast.success(t('apiNotifications.quitOrganisation'))
} catch (reason) {
@@ -53,16 +48,14 @@ const Organisations = ({ membership }: OrganisationsProps) => {
try {
await acceptOrganisationInvitation(membership.id)
- dispatch(
- authActions.mergeUser({
- organisationMemberships: _map(user.organisationMemberships, (item) => {
- if (item.id === membership.id) {
- return { ...item, confirmed: true }
- }
- return item
- }),
+ mergeUser({
+ organisationMemberships: _map(user?.organisationMemberships, (item) => {
+ if (item.id === membership.id) {
+ return { ...item, confirmed: true }
+ }
+ return item
}),
- )
+ })
toast.success(t('apiNotifications.acceptInvitation'))
} catch (reason) {
diff --git a/web/app/pages/UserSettings/components/ProjectList.tsx b/web/app/pages/UserSettings/components/ProjectList.tsx
index 8601d6ff3..de58d9596 100644
--- a/web/app/pages/UserSettings/components/ProjectList.tsx
+++ b/web/app/pages/UserSettings/components/ProjectList.tsx
@@ -3,13 +3,11 @@ import _filter from 'lodash/filter'
import _map from 'lodash/map'
import { memo, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { toast } from 'sonner'
import { rejectProjectShare, acceptProjectShare } from '~/api'
import { SharedProject } from '~/lib/models/SharedProject'
-import { authActions } from '~/lib/reducers/auth'
-import { StateType, useAppDispatch } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Button from '~/ui/Button'
import Modal from '~/ui/Modal'
@@ -22,8 +20,7 @@ const ProjectList = ({ item }: ProjectListProps) => {
t,
i18n: { language },
} = useTranslation('common')
- const { user } = useSelector((state: StateType) => state.auth)
- const dispatch = useAppDispatch()
+ const { user, mergeUser } = useAuth()
const [showDeleteModal, setShowDeleteModal] = useState(false)
const { created, confirmed, id, role, project } = item
@@ -31,11 +28,9 @@ const ProjectList = ({ item }: ProjectListProps) => {
const onQuit = async () => {
try {
await rejectProjectShare(item.id)
- dispatch(
- authActions.mergeUser({
- sharedProjects: _filter(user.sharedProjects, (share) => share.id !== item.id),
- }),
- )
+ mergeUser({
+ sharedProjects: _filter(user?.sharedProjects, (share) => share.id !== item.id),
+ })
toast.success(t('apiNotifications.quitProject'))
} catch (reason) {
console.error(`[ERROR] Error while quitting project: ${reason}`)
@@ -47,16 +42,14 @@ const ProjectList = ({ item }: ProjectListProps) => {
try {
await acceptProjectShare(id)
- dispatch(
- authActions.mergeUser({
- sharedProjects: _map(user.sharedProjects, (item) => {
- if (item.id === id) {
- return { ...item, confirmed: true }
- }
- return item
- }),
+ mergeUser({
+ sharedProjects: _map(user?.sharedProjects, (item) => {
+ if (item.id === id) {
+ return { ...item, confirmed: true }
+ }
+ return item
}),
- )
+ })
toast.success(t('apiNotifications.acceptInvitation'))
} catch (reason) {
diff --git a/web/app/pages/UserSettings/components/Referral.tsx b/web/app/pages/UserSettings/components/Referral.tsx
index c712201e9..1f5374ecd 100644
--- a/web/app/pages/UserSettings/components/Referral.tsx
+++ b/web/app/pages/UserSettings/components/Referral.tsx
@@ -3,7 +3,6 @@ import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
import React, { useState, useEffect } from 'react'
import { useTranslation, Trans } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { toast } from 'sonner'
import { generateRefCode, getPayoutsInfo, getReferrals, setPaypalEmail } from '~/api'
@@ -19,8 +18,7 @@ import {
REFERRAL_CUT,
} from '~/lib/constants'
import { User } from '~/lib/models/User'
-import { authActions } from '~/lib/reducers/auth'
-import { StateType, useAppDispatch } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Button from '~/ui/Button'
import Highlighted from '~/ui/Highlighted'
import Spin from '~/ui/icons/Spin'
@@ -29,8 +27,7 @@ import Tooltip from '~/ui/Tooltip'
import { isValidEmail } from '~/utils/validator'
const Referral = () => {
- const { user } = useSelector((state: StateType) => state.auth)
- const dispatch = useAppDispatch()
+ const { user, mergeUser } = useAuth()
const {
t,
@@ -39,7 +36,7 @@ const Referral = () => {
const [refCodeGenerating, setRefCodeGenerating] = useState(false)
const [paypalInputError, setPaypalInputError] = useState<string | null>(null)
const [isPaypalEmailLoading, setIsPaypalEmailLoading] = useState(false)
- const [paypalEmailAddress, setPaypalEmailAddress] = useState<string | null>(user.paypalPaymentsEmail)
+ const [paypalEmailAddress, setPaypalEmailAddress] = useState<string | null>(user?.paypalPaymentsEmail || null)
const [referralStatistics, setReferralStatistics] = useState<{
trials: number
@@ -80,7 +77,7 @@ const Referral = () => {
}, [])
const onRefCodeGenerate = async () => {
- if (refCodeGenerating || user.refCode) {
+ if (refCodeGenerating || user?.refCode) {
return
}
@@ -88,11 +85,9 @@ const Referral = () => {
try {
const { refCode } = await generateRefCode()
- dispatch(
- authActions.mergeUser({
- refCode,
- }),
- )
+ mergeUser({
+ refCode,
+ })
} catch {
toast.error(t('apiNotifications.somethingWentWrong'))
} finally {
@@ -119,11 +114,9 @@ const Referral = () => {
try {
await setPaypalEmail(paypalEmailAddress)
- dispatch(
- authActions.mergeUser({
- paypalPaymentsEmail: paypalEmailAddress,
- }),
- )
+ mergeUser({
+ paypalPaymentsEmail: paypalEmailAddress,
+ })
toast.success(t('profileSettings.referral.payoutEmailUpdated'))
} catch (reason) {
console.error('[Referral][updatePaypalEmail] Something went wrong whilst updating paypal email', reason)
@@ -175,7 +168,7 @@ const Referral = () => {
<p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
{t('profileSettings.referral.referralLinkDesc')}
</p>
- {user.refCode ? (
+ {user?.refCode ? (
<div className='grid grid-cols-1 gap-x-4 gap-y-6 lg:grid-cols-2'>
<Input
label={t('profileSettings.referral.yourReferralLink')}
diff --git a/web/app/pages/UserSettings/components/Socialisations.tsx b/web/app/pages/UserSettings/components/Socialisations.tsx
index 3b02ca9e5..02d52a34e 100644
--- a/web/app/pages/UserSettings/components/Socialisations.tsx
+++ b/web/app/pages/UserSettings/components/Socialisations.tsx
@@ -2,14 +2,12 @@ import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/solid'
import _map from 'lodash/map'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { toast } from 'sonner'
-import { authMe, generateSSOAuthURL, linkBySSOHash, unlinkSSO } from '~/api'
+import { generateSSOAuthURL, linkBySSOHash, unlinkSSO } from '~/api'
import { SSO_PROVIDERS } from '~/lib/constants'
import { User } from '~/lib/models/User'
-import { authActions } from '~/lib/reducers/auth'
-import { StateType, useAppDispatch } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
import Button from '~/ui/Button'
import GithubDark from '~/ui/icons/GithubDark'
@@ -37,7 +35,11 @@ const AVAILABLE_SSO_PROVIDERS = [
},
]
-const getStatusByUser = (user: User, socialisation: string) => {
+const getStatusByUser = (user: User | null, socialisation: string) => {
+ if (!user) {
+ return [false, false]
+ }
+
if (socialisation === SSO_PROVIDERS.GOOGLE) {
const connected = user.googleId
const unlinkable = !user.registeredWithGoogle
@@ -56,9 +58,8 @@ const getStatusByUser = (user: User, socialisation: string) => {
const HASH_CHECK_FREQUENCY = 1000 // 1 second
const Socialisations = () => {
- const { user } = useSelector((state: StateType) => state.auth)
+ const { user, loadUser } = useAuth()
const { theme } = useTheme()
- const dispatch = useAppDispatch()
const { t } = useTranslation('common')
const [isLoading, setIsLoading] = useState(false)
@@ -88,8 +89,7 @@ const Socialisations = () => {
await linkBySSOHash(uuid, provider)
authWindow.close()
- const { user } = await authMe()
- dispatch(authActions.authSuccessful(user))
+ await loadUser()
toast.success(t('apiNotifications.socialAccountLinked'))
@@ -116,8 +116,7 @@ const Socialisations = () => {
try {
await unlinkSSO(provider)
- const { user } = await authMe()
- dispatch(authActions.authSuccessful(user))
+ await loadUser()
toast.success(t('apiNotifications.socialAccountUninked'))
} catch (reason) {
diff --git a/web/app/pages/UserSettings/components/TwoFA.tsx b/web/app/pages/UserSettings/components/TwoFA.tsx
index 38702eee0..d6a8f8f0a 100644
--- a/web/app/pages/UserSettings/components/TwoFA.tsx
+++ b/web/app/pages/UserSettings/components/TwoFA.tsx
@@ -4,20 +4,17 @@ import _isString from 'lodash/isString'
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import QRCode from 'react-qr-code'
-import { useSelector } from 'react-redux'
import { toast } from 'sonner'
import { generate2FA, enable2FA, disable2FA } from '~/api'
-import { authActions } from '~/lib/reducers/auth'
-import { StateType, useAppDispatch } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
import { setAccessToken } from '~/utils/accessToken'
import { setRefreshToken } from '~/utils/refreshToken'
const TwoFA = () => {
- const dispatch = useAppDispatch()
- const { user, dontRemember } = useSelector((state: StateType) => state.auth)
+ const { user, mergeUser } = useAuth()
const { t } = useTranslation('common')
const [twoFAConfigurating, setTwoFAConfigurating] = useState(false)
@@ -30,7 +27,7 @@ const TwoFA = () => {
const [twoFACode, setTwoFACode] = useState('')
const [twoFACodeError, setTwoFACodeError] = useState<string | null>(null)
const [twoFARecovery, setTwoFARecovery] = useState<string | null>(null)
- const { isTwoFactorAuthenticationEnabled } = user
+ const { isTwoFactorAuthenticationEnabled } = user || {}
const handle2FAInput = (event: React.ChangeEvent<HTMLInputElement>) => {
const {
@@ -70,8 +67,9 @@ const TwoFA = () => {
try {
const { twoFactorRecoveryCode, accessToken, refreshToken } = await enable2FA(twoFACode)
setRefreshToken(refreshToken)
- setAccessToken(accessToken, dontRemember)
- dispatch(authActions.mergeUser({ isTwoFactorAuthenticationEnabled: true }))
+ // TODO: Should probably pass dontRemember here if user session is temporary
+ setAccessToken(accessToken)
+ mergeUser({ isTwoFactorAuthenticationEnabled: true })
setTwoFARecovery(twoFactorRecoveryCode)
} catch (reason) {
if (_isString(reason)) {
@@ -91,7 +89,7 @@ const TwoFA = () => {
try {
await disable2FA(twoFACode)
- dispatch(authActions.mergeUser({ isTwoFactorAuthenticationEnabled: false }))
+ mergeUser({ isTwoFactorAuthenticationEnabled: false })
} catch (reason) {
if (_isString(reason)) {
toast.error(reason)
diff --git a/web/app/providers/AuthProvider.tsx b/web/app/providers/AuthProvider.tsx
new file mode 100644
index 000000000..5b6434b34
--- /dev/null
+++ b/web/app/providers/AuthProvider.tsx
@@ -0,0 +1,110 @@
+import { createContext, useCallback, useContext, useEffect, useState } from 'react'
+
+import { authMe } from '~/api'
+import { User } from '~/lib/models/User'
+import { logout as logoutCookies } from '~/utils/auth'
+
+interface AuthContextType {
+ isAuthenticated: boolean
+ isLoading: boolean
+ user: User | null
+ totalMonthlyEvents: number
+ logout: (invalidateAllSessions?: boolean) => void
+ setUser: (user: User) => void
+ mergeUser: (newUser: Partial<User>) => void
+ setTotalMonthlyEvents: (totalMonthlyEvents: number) => void
+ loadUser: (signal?: AbortSignal) => Promise<void>
+}
+
+const AuthContext = createContext<AuthContextType | undefined>(undefined)
+
+interface AuthProviderProps {
+ children: React.ReactNode
+ initialIsAuthenticated: boolean
+}
+
+export const AuthProvider = ({ children, initialIsAuthenticated }: AuthProviderProps) => {
+ const [isAuthenticated, setIsAuthenticated] = useState(initialIsAuthenticated)
+ const [isLoading, setIsLoading] = useState(true)
+ const [user, setUser] = useState<User | null>(null)
+
+ // TODO: @deprecated
+ const [totalMonthlyEvents, setTotalMonthlyEvents] = useState(0)
+
+ const logout = useCallback((invalidateAllSessions?: boolean) => {
+ setIsAuthenticated(false)
+ setUser(null)
+ logoutCookies(invalidateAllSessions)
+ }, [])
+
+ const mergeUser = useCallback((newUser: Partial<User>) => {
+ setUser((prev) => {
+ if (!prev) {
+ return null
+ }
+
+ return { ...prev, ...newUser }
+ })
+ }, [])
+
+ const loadUser = useCallback(
+ async (signal?: AbortSignal) => {
+ try {
+ const { user, totalMonthlyEvents } = await authMe({ signal })
+ setUser(user)
+ setTotalMonthlyEvents(totalMonthlyEvents)
+ } catch (error) {
+ if (error instanceof Error && error.name === 'AbortError') {
+ return
+ }
+
+ logout()
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [logout],
+ )
+
+ useEffect(() => {
+ if (!initialIsAuthenticated) {
+ setIsLoading(false)
+ return
+ }
+
+ const abortController = new AbortController()
+
+ loadUser(abortController.signal)
+
+ return () => abortController.abort()
+ }, [initialIsAuthenticated, loadUser])
+
+ return (
+ <AuthContext.Provider
+ value={{
+ //
+ isAuthenticated,
+ user,
+ isLoading,
+ logout,
+ totalMonthlyEvents,
+ setTotalMonthlyEvents,
+ setUser,
+ mergeUser,
+ loadUser,
+ }}
+ >
+ {children}
+ </AuthContext.Provider>
+ )
+}
+
+export const useAuth = () => {
+ const context = useContext(AuthContext)
+
+ if (context === undefined) {
+ throw new Error('useAuth must be used within a AuthProvider')
+ }
+
+ return context
+}
diff --git a/web/app/providers/CurrentProjectProvider.tsx b/web/app/providers/CurrentProjectProvider.tsx
index f84820abb..739ed980c 100644
--- a/web/app/providers/CurrentProjectProvider.tsx
+++ b/web/app/providers/CurrentProjectProvider.tsx
@@ -1,26 +1,26 @@
import _replace from 'lodash/replace'
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
import { useNavigate, useSearchParams } from 'react-router'
import { toast } from 'sonner'
-import { checkPassword, getProject } from '~/api'
-import { LS_PROJECTS_PROTECTED_KEY } from '~/lib/constants'
-import { type Project } from '~/lib/models/Project'
-import { type StateType } from '~/lib/store'
+import { checkPassword, getInstalledExtensions, getProject } from '~/api'
+import { isSelfhosted, LS_PROJECTS_PROTECTED_KEY } from '~/lib/constants'
+import { Extension, type Project } from '~/lib/models/Project'
import { getItem, removeItem } from '~/utils/localstorage'
import routes from '~/utils/routes'
import { getProjectPreferences, setProjectPreferences } from '../pages/Project/View/utils/cache'
import { CHART_METRICS_MAPPING } from '../pages/Project/View/ViewProject.helpers'
+import { useAuth } from './AuthProvider'
import { useTheme } from './ThemeProvider'
interface CurrentProjectContextType {
id: string
project: Project | null
preferences: ProjectPreferences
+ extensions: Extension[]
updatePreferences: (prefs: ProjectPreferences) => void
}
@@ -52,7 +52,7 @@ const useProject = (id: string) => {
const { theme } = useTheme()
const { t } = useTranslation('common')
const navigate = useNavigate()
- const { loading: authLoading } = useSelector((state: StateType) => state.auth)
+ const { isLoading: authLoading } = useAuth()
const projectPassword = useProjectPassword(id)
const isEmbedded = useIsEmbedded()
const [project, setProject] = useState<Project | null>(null)
@@ -139,9 +139,30 @@ const useProjectPreferences = (id: string) => {
export const CurrentProjectProvider = ({ children, id }: CurrentProjectProviderProps) => {
const project = useProject(id)
+ const { isAuthenticated } = useAuth()
const { preferences, updatePreferences } = useProjectPreferences(id)
+ const [extensions, setExtensions] = useState<Extension[]>([])
+
+ useEffect(() => {
+ if (!project || isSelfhosted || !isAuthenticated) {
+ return
+ }
+
+ const abortController = new AbortController()
+
+ getInstalledExtensions(100, 0, { signal: abortController.signal })
+ .then(({ extensions }) => {
+ setExtensions(extensions)
+ })
+ .catch((reason) => {
+ console.error('[ERROR] (CurrentProjectProvider -> getInstalledExtensions)', reason)
+ })
+
+ return () => abortController.abort()
+ }, [project, isAuthenticated])
+
return (
- <CurrentProjectContext.Provider value={{ id, project, preferences, updatePreferences }}>
+ <CurrentProjectContext.Provider value={{ id, project, preferences, updatePreferences, extensions }}>
{children}
</CurrentProjectContext.Provider>
)
diff --git a/web/app/root.tsx b/web/app/root.tsx
index c6c176c1c..7f412e617 100644
--- a/web/app/root.tsx
+++ b/web/app/root.tsx
@@ -6,7 +6,6 @@ import FlatpickrLightCss from 'flatpickr/dist/themes/light.css?url'
import _replace from 'lodash/replace'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { Provider } from 'react-redux'
import type { LinksFunction, LoaderFunctionArgs, HeadersFunction } from 'react-router'
import {
redirect,
@@ -24,7 +23,6 @@ import { ExternalScripts } from 'remix-utils/external-scripts'
import { LocaleLinks } from '~/components/LocaleLinks'
import { SEO } from '~/components/SEO'
import { CONTACT_EMAIL, LS_THEME_SETTING, isSelfhosted, I18N_CACHE_BREAKER } from '~/lib/constants'
-import { store } from '~/lib/store'
import FlatpickerCss from '~/styles/Flatpicker.css?url'
import FontsCss from '~/styles/fonts.css?url'
import mainCss from '~/styles/index.css?url'
@@ -36,6 +34,7 @@ import { detectTheme, isAuthenticated, isWWW } from '~/utils/server'
import AppWrapper from './App'
import { detectLanguage } from './i18n'
+import { AuthProvider } from './providers/AuthProvider'
import { ThemeProvider, useTheme } from './providers/ThemeProvider'
trackViews()
@@ -199,9 +198,9 @@ const Body = () => {
return (
<body className={cx(theme, { 'bg-white': theme === 'light', 'bg-slate-900': theme === 'dark' })}>
- <Provider store={store}>
- <AppWrapper ssrAuthenticated={isAuthed} />
- </Provider>
+ <AuthProvider initialIsAuthenticated={isAuthed}>
+ <AppWrapper />
+ </AuthProvider>
<ScrollRestoration />
<ExternalScripts />
<Scripts />
diff --git a/web/app/routes/_index.tsx b/web/app/routes/_index.tsx
index 4beb0e6d9..58f7a8aae 100644
--- a/web/app/routes/_index.tsx
+++ b/web/app/routes/_index.tsx
@@ -7,7 +7,6 @@ import _map from 'lodash/map'
import { Cookie, FileTextIcon } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { useTranslation, Trans } from 'react-i18next'
-import { useSelector } from 'react-redux'
import type { LoaderFunctionArgs } from 'react-router'
import { useLoaderData, Link, redirect } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
@@ -25,7 +24,6 @@ import Pricing from '~/components/marketing/Pricing'
import {
GITHUB_URL,
LIVE_DEMO_URL,
- isBrowser,
isSelfhosted,
OS_LOGO_MAP,
OS_LOGO_MAP_DARK,
@@ -34,11 +32,10 @@ import {
} from '~/lib/constants'
import { DEFAULT_METAINFO, Metainfo } from '~/lib/models/Metainfo'
import { Stats } from '~/lib/models/Stats'
-import { StateType } from '~/lib/store/index'
import CCRow from '~/pages/Project/View/components/CCRow'
import { MetricCard, MetricCardSelect } from '~/pages/Project/View/components/MetricCards'
+import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
-import { getAccessToken } from '~/utils/accessToken'
import { getStringFromTime, getTimeFromSeconds } from '~/utils/generic'
import routesPath from '~/utils/routes'
import { isAuthenticated } from '~/utils/server'
@@ -797,7 +794,7 @@ const CoreFeatures = () => {
)
}
-const Hero = ({ authenticated }: { authenticated: boolean }) => {
+const Hero = () => {
const { theme } = useTheme()
const { t } = useTranslation('common')
@@ -832,7 +829,7 @@ const Hero = ({ authenticated }: { authenticated: boolean }) => {
}}
/>
</div>
- <Header authenticated={authenticated} transparent />
+ <Header transparent />
<div className='relative mx-auto min-h-[740px] pt-10 pb-5 sm:px-3 lg:px-6 lg:pt-24 xl:px-8'>
<div className='relative z-20 flex flex-col content-between justify-center'>
<div className='relative mx-auto flex flex-col px-4 text-left'>
@@ -895,17 +892,13 @@ const Hero = ({ authenticated }: { authenticated: boolean }) => {
}
export default function Index() {
- const { isAuth } = useLoaderData<typeof loader>()
-
const { theme } = useTheme()
- const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)
- const accessToken = getAccessToken()
- const authenticated = isBrowser ? (loading ? !!accessToken : reduxAuthenticated) : isAuth
+ const { isAuthenticated } = useAuth()
return (
<div className='overflow-hidden'>
<main className='bg-white dark:bg-slate-900'>
- <Hero authenticated={authenticated} />
+ <Hero />
<Problem />
@@ -928,7 +921,7 @@ export default function Index() {
<CoreFeatures />
{/* Hiding the Pricing for authenticated users on the main page as the Paddle script only loads on the Billing page */}
- {!authenticated ? <Pricing authenticated={false} /> : null}
+ {!isAuthenticated ? <Pricing authenticated={false} /> : null}
<Feedback
name='Alper Alkan'
diff --git a/web/app/routes/billing.tsx b/web/app/routes/billing.tsx
index aea4fb345..ecc5ed8d5 100644
--- a/web/app/routes/billing.tsx
+++ b/web/app/routes/billing.tsx
@@ -1,27 +1,21 @@
-import type { LoaderFunctionArgs } from 'react-router'
-import { useLoaderData, data, redirect } from 'react-router'
+import { redirect } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
import { isSelfhosted } from '~/lib/constants'
import Billing from '~/pages/Billing'
-import { isAuthenticated } from '~/utils/server'
export const sitemap: SitemapFunction = () => ({
exclude: true,
})
-export async function loader({ request }: LoaderFunctionArgs) {
+export async function loader() {
if (isSelfhosted) {
return redirect('/login', 302)
}
- const isAuth = isAuthenticated(request)
-
- return data({ isAuth })
+ return null
}
-export default function Index() {
- const { isAuth } = useLoaderData<any>()
-
- return <Billing ssrAuthenticated={isAuth} />
+export default function BillingRoute() {
+ return <Billing />
}
diff --git a/web/app/routes/error-tracking.tsx b/web/app/routes/error-tracking.tsx
index 5bd94718b..315e02993 100644
--- a/web/app/routes/error-tracking.tsx
+++ b/web/app/routes/error-tracking.tsx
@@ -1,28 +1,22 @@
-import type { LoaderFunctionArgs } from 'react-router'
-import { useLoaderData, redirect } from 'react-router'
+import { redirect } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
import { isDisableMarketingPages, isSelfhosted } from '~/lib/constants'
import ErrorTracking from '~/pages/ErrorTracking'
-import { isAuthenticated } from '~/utils/server'
export const sitemap: SitemapFunction = () => ({
priority: 1,
exclude: isSelfhosted || isDisableMarketingPages,
})
-export async function loader({ request }: LoaderFunctionArgs) {
+export async function loader() {
if (isSelfhosted || isDisableMarketingPages) {
return redirect('/login', 302)
}
- const isAuth = isAuthenticated(request)
-
- return { isAuth }
+ return null
}
-export default function Index() {
- const { isAuth } = useLoaderData<typeof loader>()
-
- return <ErrorTracking ssrAuthenticated={isAuth} />
+export default function ErrorTrackingRoute() {
+ return <ErrorTracking />
}
diff --git a/web/app/routes/feature-flags.tsx b/web/app/routes/feature-flags.tsx
index f24744249..a0b579a4c 100644
--- a/web/app/routes/feature-flags.tsx
+++ b/web/app/routes/feature-flags.tsx
@@ -2,28 +2,25 @@ import { Switch } from '@headlessui/react'
import cx from 'clsx'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { useDispatch, useSelector } from 'react-redux'
import { useNavigate } from 'react-router'
import { toast } from 'sonner'
import { setFeatureFlags } from '~/api'
import { withAuthentication, auth } from '~/hoc/protected'
import { FeatureFlag } from '~/lib/models/User'
-import { authActions } from '~/lib/reducers/auth'
-import { StateType } from '~/lib/store'
+import { useAuth } from '~/providers/AuthProvider'
import Loader from '~/ui/Loader'
import routes from '~/utils/routes'
const FeatureFlagsPage = () => {
const { t } = useTranslation('common')
- const { user, loading } = useSelector((state: StateType) => state.auth)
+ const { user, isLoading, mergeUser } = useAuth()
const [flags, setFlags] = useState<FeatureFlag[]>([])
const [initialised, setInitialised] = useState(false)
const navigate = useNavigate()
- const dispatch = useDispatch()
useEffect(() => {
- if (loading || initialised) {
+ if (isLoading || initialised) {
return
}
@@ -34,7 +31,7 @@ const FeatureFlagsPage = () => {
}
navigate(routes.main)
- }, [loading, user, navigate, initialised])
+ }, [isLoading, user, navigate, initialised])
const handleToggle = async (flag: FeatureFlag) => {
try {
@@ -42,7 +39,7 @@ const FeatureFlagsPage = () => {
await setFeatureFlags(newFlags)
setFlags(newFlags)
- dispatch(authActions.mergeUser({ featureFlags: newFlags }))
+ mergeUser({ featureFlags: newFlags })
toast.success(t('featureFlags.updated'))
} catch (error) {
console.error('Failed to update feature flags:', error)
@@ -50,7 +47,7 @@ const FeatureFlagsPage = () => {
}
}
- if (loading) {
+ if (isLoading) {
return (
<div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>
<Loader />
diff --git a/web/app/routes/performance.tsx b/web/app/routes/performance.tsx
index 7cbc12447..e866e3a90 100644
--- a/web/app/routes/performance.tsx
+++ b/web/app/routes/performance.tsx
@@ -1,28 +1,22 @@
-import type { LoaderFunctionArgs } from 'react-router'
-import { useLoaderData, redirect } from 'react-router'
+import { redirect } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
import { isDisableMarketingPages, isSelfhosted } from '~/lib/constants'
import Performance from '~/pages/Performance'
-import { isAuthenticated } from '~/utils/server'
export const sitemap: SitemapFunction = () => ({
priority: 1,
exclude: isSelfhosted || isDisableMarketingPages,
})
-export async function loader({ request }: LoaderFunctionArgs) {
+export async function loader() {
if (isSelfhosted || isDisableMarketingPages) {
return redirect('/login', 302)
}
- const isAuth = isAuthenticated(request)
-
- return { isAuth }
+ return null
}
export default function PerformanceRoute() {
- const { isAuth } = useLoaderData<typeof loader>()
-
- return <Performance ssrAuthenticated={isAuth} />
+ return <Performance />
}
diff --git a/web/app/routes/projects.$id.password.tsx b/web/app/routes/projects.$id.password.tsx
index 85491c35f..352a1b481 100644
--- a/web/app/routes/projects.$id.password.tsx
+++ b/web/app/routes/projects.$id.password.tsx
@@ -2,20 +2,18 @@ import type { LoaderFunctionArgs } from 'react-router'
import { useLoaderData } from 'react-router'
import ProjectProtectedPassword from '~/pages/Project/ProjectProtectedPassword'
-import { isEmbedded, isAuthenticated } from '~/utils/server'
+import { isEmbedded } from '~/utils/server'
export async function loader({ request }: LoaderFunctionArgs) {
const embedded = isEmbedded(request)
- const isAuth = isAuthenticated(request)
return {
embedded,
- isAuth,
}
}
export default function ProjectProtectedPasswordRoute() {
- const { embedded, isAuth } = useLoaderData<typeof loader>()
+ const { embedded } = useLoaderData<typeof loader>()
- return <ProjectProtectedPassword embedded={embedded} isAuth={isAuth} />
+ return <ProjectProtectedPassword embedded={embedded} />
}
diff --git a/web/app/routes/projects.$id.tsx b/web/app/routes/projects.$id.tsx
index 1a9007646..afccd79af 100644
--- a/web/app/routes/projects.$id.tsx
+++ b/web/app/routes/projects.$id.tsx
@@ -6,7 +6,7 @@ import { API_URL } from '~/lib/constants'
import ViewProject from '~/pages/Project/View'
import { CurrentProjectProvider } from '~/providers/CurrentProjectProvider'
import ProjectViewStyle from '~/styles/ProjectViewStyle.css?url'
-import { isEmbedded, isAuthenticated, getProjectTabs } from '~/utils/server'
+import { isEmbedded, getProjectTabs } from '~/utils/server'
export const links: LinksFunction = () => [{ rel: 'stylesheet', href: ProjectViewStyle }]
@@ -23,12 +23,10 @@ export const meta: MetaFunction = ({ location }) => {
export async function loader({ request }: LoaderFunctionArgs) {
const embedded = isEmbedded(request)
- const isAuth = isAuthenticated(request)
const tabs = getProjectTabs(request)
return {
embedded,
- isAuth,
tabs,
}
}
diff --git a/web/app/ui/icons/SwetrixLogo.tsx b/web/app/ui/icons/SwetrixLogo.tsx
index e25f9c60d..4547f1ce2 100644
--- a/web/app/ui/icons/SwetrixLogo.tsx
+++ b/web/app/ui/icons/SwetrixLogo.tsx
@@ -1,18 +1,21 @@
import cx from 'clsx'
import { useTranslation } from 'react-i18next'
-import { isSelfhosted } from '~/lib/constants'
+import { isSelfhosted, ThemeType } from '~/lib/constants'
import { useTheme } from '~/providers/ThemeProvider'
interface SwetrixLogoProps {
className?: string
lazy?: boolean
+ theme?: ThemeType
}
-const SwetrixLogo = ({ className, lazy }: SwetrixLogoProps) => {
- const { theme } = useTheme()
+const SwetrixLogo = ({ className, lazy, theme: themeOverride }: SwetrixLogoProps) => {
+ const { theme: currentTheme } = useTheme()
const { t } = useTranslation()
+ const theme = themeOverride || currentTheme
+
return (
<div className={cx('flex -translate-y-[2px] items-center gap-2 select-none', className)}>
<img
diff --git a/web/package-lock.json b/web/package-lock.json
index 02b485949..9199b493e 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -4,7 +4,6 @@
"requires": true,
"packages": {
"": {
- "name": "web",
"license": "AGPL-3.0",
"dependencies": {
"@headlessui/react": "^2.2.0",
@@ -15,7 +14,6 @@
"@react-router/fs-routes": "^7.1.5",
"@react-router/node": "^7.1.5",
"@react-router/serve": "^7.1.5",
- "@reduxjs/toolkit": "^2.5.1",
"@swetrix/sdk": "^1.1.0",
"@tailwindcss/vite": "^4.0.9",
"@types/ua-parser-js": "^0.7.39",
@@ -49,9 +47,7 @@
"react-i18next": "^15.4.1",
"react-outside-click-handler": "^1.3.0",
"react-qr-code": "^2.0.15",
- "react-redux": "^9.2.0",
"react-router": "^7.1.5",
- "redux": "^5.0.1",
"remix-i18next": "^7.0.2",
"remix-sitemap": "^3.2.0",
"remix-utils": "^8.1.0",
@@ -2324,30 +2320,6 @@
"react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1"
}
},
- "node_modules/@reduxjs/toolkit": {
- "version": "2.5.1",
- "resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.5.1.tgz",
- "integrity": "sha512-UHhy3p0oUpdhnSxyDjaRDYaw8Xra75UiLbCiRozVPHjfDwNYkh0TsVm/1OmTW8Md+iDAJmYPWUKMvsMc2GtpNg==",
- "license": "MIT",
- "dependencies": {
- "immer": "^10.0.3",
- "redux": "^5.0.1",
- "redux-thunk": "^3.1.0",
- "reselect": "^5.1.0"
- },
- "peerDependencies": {
- "react": "^16.9.0 || ^17.0.0 || ^18 || ^19",
- "react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0"
- },
- "peerDependenciesMeta": {
- "react": {
- "optional": true
- },
- "react-redux": {
- "optional": true
- }
- }
- },
"node_modules/@remix-run/router": {
"version": "1.23.0",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.0.tgz",
@@ -3408,12 +3380,6 @@
"integrity": "sha512-P/oDfpofrdtF5xw433SPALpdSchtJmY7nsJItf8h3KXqOslkbySh8zq4dSWXH2oTjRvJ5PczVEoCZPow6GicLg==",
"license": "MIT"
},
- "node_modules/@types/use-sync-external-store": {
- "version": "0.0.6",
- "resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",
- "integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==",
- "license": "MIT"
- },
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.26.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.26.0.tgz",
@@ -7056,16 +7022,6 @@
"integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==",
"license": "MIT"
},
- "node_modules/immer": {
- "version": "10.1.1",
- "resolved": "https://registry.npmjs.org/immer/-/immer-10.1.1.tgz",
- "integrity": "sha512-s2MPrmjovJcoMaHtx6K11Ra7oD05NT97w1IC5zpMkT6Atjr7H8LjaDd81iIxUYpMKSRRNMJE703M1Fhr/TctHw==",
- "license": "MIT",
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/immer"
- }
- },
"node_modules/import-fresh": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
@@ -9419,29 +9375,6 @@
"react": "*"
}
},
- "node_modules/react-redux": {
- "version": "9.2.0",
- "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz",
- "integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==",
- "license": "MIT",
- "dependencies": {
- "@types/use-sync-external-store": "^0.0.6",
- "use-sync-external-store": "^1.4.0"
- },
- "peerDependencies": {
- "@types/react": "^18.2.25 || ^19",
- "react": "^18.0 || ^19",
- "redux": "^5.0.0"
- },
- "peerDependenciesMeta": {
- "@types/react": {
- "optional": true
- },
- "redux": {
- "optional": true
- }
- }
- },
"node_modules/react-refresh": {
"version": "0.14.2",
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.14.2.tgz",
@@ -9518,21 +9451,6 @@
"url": "https://paulmillr.com/funding/"
}
},
- "node_modules/redux": {
- "version": "5.0.1",
- "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
- "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
- "license": "MIT"
- },
- "node_modules/redux-thunk": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-3.1.0.tgz",
- "integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==",
- "license": "MIT",
- "peerDependencies": {
- "redux": "^5.0.0"
- }
- },
"node_modules/reflect.getprototypeof": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
@@ -9676,12 +9594,6 @@
"node": ">=0.10.0"
}
},
- "node_modules/reselect": {
- "version": "5.1.1",
- "resolved": "https://registry.npmjs.org/reselect/-/reselect-5.1.1.tgz",
- "integrity": "sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w==",
- "license": "MIT"
- },
"node_modules/resolve": {
"version": "1.22.10",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz",
@@ -11020,15 +10932,6 @@
"punycode": "^2.1.0"
}
},
- "node_modules/use-sync-external-store": {
- "version": "1.4.0",
- "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.4.0.tgz",
- "integrity": "sha512-9WXSPC5fMv61vaupRkCKCxsPxBocVnwakBEkMIHHpkTTg6icbJtg6jzgtLDm4bl3cSHAca52rYWih0k4K3PfHw==",
- "license": "MIT",
- "peerDependencies": {
- "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
- }
- },
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
diff --git a/web/package.json b/web/package.json
index 1522212ca..e1bf89a93 100644
--- a/web/package.json
+++ b/web/package.json
@@ -28,7 +28,6 @@
"@react-router/fs-routes": "^7.1.5",
"@react-router/node": "^7.1.5",
"@react-router/serve": "^7.1.5",
- "@reduxjs/toolkit": "^2.5.1",
"@swetrix/sdk": "^1.1.0",
"@tailwindcss/vite": "^4.0.9",
"@types/ua-parser-js": "^0.7.39",
@@ -62,9 +61,7 @@
"react-i18next": "^15.4.1",
"react-outside-click-handler": "^1.3.0",
"react-qr-code": "^2.0.15",
- "react-redux": "^9.2.0",
"react-router": "^7.1.5",
- "redux": "^5.0.1",
"remix-i18next": "^7.0.2",
"remix-sitemap": "^3.2.0",
"remix-utils": "^8.1.0",