Skip to content

Commit

Permalink
refactor: created AccountProvider and useEnvironment
Browse files Browse the repository at this point in the history
  • Loading branch information
Nabhag8848 committed May 15, 2024
1 parent 78e5498 commit 5099fa6
Show file tree
Hide file tree
Showing 7 changed files with 109 additions and 66 deletions.
54 changes: 54 additions & 0 deletions packages/client/src/context/AccountProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import React, { ReactNode, createContext, useContext, useEffect, useState } from 'react';
import * as Sentry from '@sentry/react';
import { useUser } from '@clerk/clerk-react';
import { useEnvironment } from '../hooks';
import { DEFAULT_ENV, REVERT_BASE_API_URL } from '../constants';

const AccountContext = createContext<any>({});

interface Props {
children?: ReactNode;
}

export function AccountProvider({ children }: Props) {
const [account, setAccount] = useState<any>();
const { user, isLoaded, isSignedIn } = useUser();
const { setEnvironment } = useEnvironment();

useEffect(() => {
if (isLoaded && isSignedIn) {
const headers = new Headers();
headers.append('Content-Type', 'application/json');

const data = JSON.stringify({
userId: user.id,
});

const requestOptions = {
method: 'POST',
body: data,
headers: headers,
};
fetch(`${REVERT_BASE_API_URL}/internal/account`, requestOptions)
.then((response) => response.json())
.then((result) => {
setAccount(result?.account);
const environments: string[] = result?.account?.environments?.map((env) => env.env) || [];
setEnvironment(environments?.[0] || DEFAULT_ENV);
})
.catch((error) => {
Sentry.captureException(error);
console.error('error', error);
});
}
}, [account, isLoaded, isSignedIn, setEnvironment, user?.id]);

return <AccountContext.Provider value={{ account }}>{children}</AccountContext.Provider>;
}

export function useAccount() {
const context = useContext(AccountContext);
if (context === undefined) throw new Error('Context was used out of Provider');

return context;
}
10 changes: 6 additions & 4 deletions packages/client/src/home/environmentSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ import * as React from 'react';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import Select, { SelectChangeEvent } from '@mui/material/Select';
import { useEnvironment } from '../hooks';

export default function EnvironmentSelector({ environmentList }) {
const { environment, setEnvironment } = useEnvironment();

export default function EnvironmentSelector({ environmentProp, setEnvironmentProp, environmentList }) {
const handleChange = (event: SelectChangeEvent) => {
event.preventDefault();
setEnvironmentProp(event.target.value);
setEnvironment(event.target.value);
};
const anchorRef = React.useRef<HTMLDivElement>(null);
return (
Expand All @@ -18,8 +21,7 @@ export default function EnvironmentSelector({ environmentProp, setEnvironmentPro
}}
labelId="environment-selector"
id="environment-selector"
value={environmentProp}
defaultValue={environmentProp}
value={environment}
onChange={handleChange}
SelectDisplayProps={{
style: {
Expand Down
75 changes: 21 additions & 54 deletions packages/client/src/home/index.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import React, { useEffect } from 'react';
import React, { useEffect, useMemo } from 'react';
import Navbar from './navbar';
import ApiKeys from './apiKeys';
import Analytics from './analytics';

import Onboarding from './onboarding';
import Integrations from './integrations';
import { useUser } from '@clerk/clerk-react';
import { REVERT_BASE_API_URL, DEFAULT_ENV } from '../constants';
import * as Sentry from '@sentry/react';
import Sidebar from '../ui/Sidebar';
import { useEnvironment } from '../hooks';

declare global {
interface Window {
Expand All @@ -27,56 +26,31 @@ const renderTab = (tabValue: number, handleChange, environment) => {
return <ApiKeys environment={environment} />;
} else return undefined;
};
const getInitialEnvironment = () => {
var selectedOption = localStorage.getItem('revert_environment_selected') || DEFAULT_ENV;

return selectedOption;
};

const Home = () => {
const [tabValue, setTabValue] = React.useState(0);
const [account, setAccount] = React.useState<any>();
const [environment, setEnvironment] = React.useState<string>(getInitialEnvironment());
const user = useUser();
const { environment } = useEnvironment();
const { user } = useUser();

const setSelectedEnvironment = (option) => {
localStorage.setItem('revert_environment_selected', option);
setEnvironment(option);
};
useEffect(() => {
if (window.Intercom) {
window.Intercom('boot', {
const IntercomParams = useMemo(
function () {
return {
api_base: 'https://api-iam.intercom.io',
app_id: process.env.REACT_APP_INTERCOM_APP_ID,
user_id: user.user?.id, //
name: user.user?.fullName, // Full name
email: user.user?.emailAddresses[0].emailAddress, // Email address
created_at: user.user?.createdAt, // Signup date as a Unix timestamp
});
}
const headers = new Headers();
headers.append('Content-Type', 'application/json');
user_id: user?.id, //
name: user?.fullName, // Full name
email: user?.emailAddresses[0].emailAddress, // Email address
created_at: user?.createdAt, // Signup date as a Unix timestamp
};
},
[user]
);

const data = JSON.stringify({
userId: user.user?.id,
});
const requestOptions = {
method: 'POST',
body: data,
headers: headers,
};
fetch(`${REVERT_BASE_API_URL}/internal/account`, requestOptions)
.then((response) => response.json())
.then((result) => {
setAccount(result?.account);
const environments: string[] = result?.account?.environments?.map((env) => env.env) || [];
setSelectedEnvironment(environments?.[0] || DEFAULT_ENV);
})
.catch((error) => {
Sentry.captureException(error);
console.error('error', error);
});
}, [user.user?.id]);
useEffect(() => {
if (window.Intercom) {
window.Intercom('boot', IntercomParams);
}
}, [IntercomParams]);

const handleChange = (newTabValue: number) => {
setTabValue(newTabValue);
Expand All @@ -87,14 +61,7 @@ const Home = () => {

return (
<>
<Navbar
workspaceName={account?.workspaceName}
environment={environment}
setEnvironment={(env) => {
setEnvironment(env);
}}
environmentList={account?.environments}
/>
<Navbar />
<div className="flex h-[100%] bg-[#181d28] text-[#fff]">
<Sidebar values={{ tabValue, handleChange }} />
{renderTab(tabValue, handleChange, environment)}
Expand Down
13 changes: 6 additions & 7 deletions packages/client/src/home/navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,19 @@ import { Link } from 'react-router-dom';
import QuizIcon from '@mui/icons-material/Quiz';
import EnvironmentSelector from './environmentSelector';
import GitHubButton from 'react-github-btn';
import { useAccount } from '../context/AccountProvider';

const Navbar = () => {
const { account } = useAccount();

const Navbar = ({ workspaceName, environment, setEnvironment, environmentList }) => {
return (
<div id="top-navbar">
<div className="flex justify-around items-center ml-[1.5rem]">
<Link to="/" className="flex justify-evenly items-center">
<img src={Logo} alt="revert_logo" className="w-[2rem] h-[2rem] mr-[1.5rem] cursor-pointer" />
<p className="text-[#fff]">{workspaceName}</p>
<p className="text-[#fff]">{account?.workspaceName}</p>
</Link>
<EnvironmentSelector
environmentProp={environment}
setEnvironmentProp={setEnvironment}
environmentList={environmentList}
/>
<EnvironmentSelector environmentList={account?.environments} />
</div>
<div className="flex justify-center items-center">
<a
Expand Down
1 change: 1 addition & 0 deletions packages/client/src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './useEnvironment';
17 changes: 17 additions & 0 deletions packages/client/src/hooks/useEnvironment.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useEffect, useState } from 'react';
import { DEFAULT_ENV } from '../constants';

export function useEnvironment() {
const [environment, setEnvironment] = useState<string>(function () {
return localStorage.getItem('revert_environment_selected') || DEFAULT_ENV;
});

useEffect(
function () {
localStorage.setItem('revert_environment_selected', environment);
},
[environment]
);

return { environment, setEnvironment };
}
5 changes: 4 additions & 1 deletion packages/client/src/layout/AppLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Home from '../home/';
import Navbar from '../ui/Navbar';
import Main from '../ui/Main';
import Side from '../ui/Side';
import { AccountProvider } from '../context/AccountProvider';

function AppLayout() {
return (
Expand All @@ -11,7 +12,9 @@ function AppLayout() {
// <Side />
// <Main />
// </div>
<Home />
<AccountProvider>
<Home />
</AccountProvider>
);
}

Expand Down

0 comments on commit 5099fa6

Please sign in to comment.