Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Aditya Jain's Onboarding #19

Open
wants to merge 1 commit into
base: startercode
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 23 additions & 27 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,60 +1,56 @@
/* eslint-disable */
import React from "react";
import "./App.css";
import { Routes, Route } from "react-router-dom";
import axios from "axios";
import { initializeApp } from "firebase/app";
import { setPersistence, getAuth, inMemoryPersistence } from "firebase/auth";
import { useLogin, LoadingScreen, AuthProvider } from "@hex-labs/core";
import {
useLogin,
LoadingScreen,
AuthProvider,
Header,
Footer
} from "@hex-labs/core";
import { ChakraProvider, Flex, Box } from "@chakra-ui/react";

import UserData from './components/UserData';

// a little bee ascii art
// const art =
// ".' '. buzz buzz\n. . . (__\\ \n . . . -{{_(|8)\n ' . . ' ' . . ' (__/";

// Initialized the Firebase app through the credentials provided
export const app = initializeApp({
apiKey: "AIzaSyCsukUZtMkI5FD_etGfefO4Sr7fHkZM7Rg",
authDomain: "auth.hexlabs.org",
});

// Sets the Firebase persistence to in memory since we use cookies for session
// management. These cookies are set by the backend on login/logout.
setPersistence(getAuth(app), inMemoryPersistence);

// By default sends axios requests with user session cookies so that the backend
// can verify the user's identity.
axios.defaults.withCredentials = true;

export const App = () => {
// Retrieves the user's login state. This hook will also make requests to log
// the user in
const [loading, loggedIn] = useLogin(app);

// If loading, show a loading screen
if (loading) {
return <LoadingScreen />;
}

// If the user is not logged in, redirect to the login frontend with a redirect
// param so that the user can login and come back to the page they were on.
if (!loggedIn) {
window.location.href = `https://login.hexlabs.org?redirect=${window.location.href}`;
return <LoadingScreen />;
}

// Sets up the AuthProvider so that any part of the application can use the
// useAuth hook to retrieve the user's login details.
return (
<AuthProvider app={app}>

{/* Setting up our React Router to route to all the different pages we may have */}
<Routes>
<Route path="/" element={<UserData />} />
</Routes>

</AuthProvider>
<ChakraProvider>
<AuthProvider app={app}>
<Flex direction="column" minHeight="100vh">
<Header>
header.Original
</Header>
<Box flex="1">
<Routes>
<Route path="/" element={<UserData />} />
</Routes>
</Box>
<Footer/>
</Flex>
</AuthProvider>
</ChakraProvider>
);
};

Expand Down
153 changes: 120 additions & 33 deletions src/components/UserCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,51 +3,138 @@ import {
Flex,
HStack,
Text,
Modal,
ModalOverlay,
ModalContent,
ModalHeader,
ModalBody,
ModalCloseButton,
useDisclosure,
Link,
Button,
VStack,
Spinner,
} from "@chakra-ui/react";
import React from "react";
import React, { useState } from "react";
import axios from "axios";
import { apiUrl, Service } from "@hex-labs/core";

type Props = {
user: any;
};

const UserCard: React.FC<Props> = (props: Props) => {
const { isOpen, onOpen, onClose } = useDisclosure();
const [hexathons, setHexathons] = useState<any[]>([]);
const [loading, setLoading] = useState(false);

// TODO: right now, the UserCard only displays the user's name and email. Create a new modal component <UserModal> that
// pops up when the card is clicked. In this modal, list all the user's information including name, email, phoneNumber,
// and userId.
const fetchHexathons = async () => {
setLoading(true);
try {
const applicationsResponse = await axios.get(
apiUrl(Service.REGISTRATION, '/applications'),
{
params: {
filter: {
userId: props.user.userId
}
}
}
);

// TODO: Explore if you can display the email as a link to the user's email that will open up the user's
// email client and start a new email to that user. Also explore if you can provide a link to the user's resume.
const hexathonIds = applicationsResponse.data.applications.map(
(app: any) => app.hexathonId
);

// TODO: In our database structure, every user has a userId that is unique to them. This is the primary key of the user
// and is referenced in their applications to all of our hexathons. Create a button that when clicked, will retrieve all of
// the hexathons that the user has applied to. You can use the /applications endpoint of the registration service to do this
// and the /hexathons endpoint of the hexathons service to get a list of all the hexathons.
const hexathonsResponse = await axios.get(
apiUrl(Service.HEXATHONS, '/hexathons'),
{
params: {
filter: {
_id: { $in: hexathonIds }
}
}
}
);

const UserCard: React.FC<Props> = (props: Props) => {
setHexathons(hexathonsResponse.data.hexathons);
} catch (error) {
console.error('Error fetching hexathons:', error);
}
setLoading(false);
};

return (
<Box
borderWidth="1px"
rounded="lg"
boxShadow="lg"
height="175px"
fontWeight="bold"
alignItems="center"
>
<Flex padding="2" flexDirection="column">
<HStack align="flex-end" justify="space-between">
<Text fontSize='xl'>{`${props.user.name.first} ${props.user.name.last}`}</Text>
</HStack>
<Text
fontSize="sm"
fontWeight="semibold"
justifyContent="justify"
mt="2"
>
{props.user.email}
</Text>
</Flex>
</Box>
<>
<Box
borderWidth="1px"
rounded="lg"
boxShadow="lg"
height="175px"
fontWeight="bold"
alignItems="center"
cursor="pointer"
onClick={onOpen}
transition="transform 0.2s"
_hover={{ transform: 'scale(1.02)' }}
>
<Flex padding="2" flexDirection="column">
<HStack align="flex-end" justify="space-between">
<Text fontSize='xl'>{`${props.user.name.first} ${props.user.name.last}`}</Text>
</HStack>
<Text
fontSize="sm"
fontWeight="semibold"
justifyContent="justify"
mt="2"
>
{props.user.email}
</Text>
</Flex>
</Box>

<Modal isOpen={isOpen} onClose={onClose}>
<ModalOverlay />
<ModalContent>
<ModalHeader>User Details</ModalHeader>
<ModalCloseButton />
<ModalBody pb={6}>
<VStack align="start" spacing={3}>
<Text><strong>Name:</strong> {props.user.name.first} {props.user.name.last}</Text>
<Text>
<strong>Email:</strong>{' '}
<Link href={`mailto:${props.user.email}`} color="blue.500">
{props.user.email}
</Link>
</Text>
<Text><strong>Phone:</strong> {props.user.phoneNumber}</Text>
{props.user.resume && (
<Link href={props.user.resume} color="blue.500" isExternal>
View Resume
</Link>
)}

<Button colorScheme="blue" onClick={fetchHexathons} mt={4}>
View Hexathons
</Button>

{loading ? (
<Spinner />
) : (
hexathons.length > 0 && (
<VStack align="start" spacing={2}>
<Text fontWeight="bold">Applied Hexathons:</Text>
{hexathons.map((hexathon) => (
<Text key={hexathon._id}>{hexathon.name}</Text>
))}
</VStack>
)
)}
</VStack>
</ModalBody>
</ModalContent>
</Modal>
</>
);
};

Expand Down
87 changes: 37 additions & 50 deletions src/components/UserData.tsx
Original file line number Diff line number Diff line change
@@ -1,76 +1,63 @@
import React, { useEffect, useState } from "react";
import { apiUrl, Service } from "@hex-labs/core";
import { SimpleGrid, Text } from "@chakra-ui/react";
import { SimpleGrid, Text, Button, HStack } from "@chakra-ui/react";
import axios from "axios";
import UserCard from "./UserCard";

const UserData: React.FC = () => {

// The useState hook is used to store state in a functional component. The
// first argument is the initial value of the state, and the second argument
// is a function that can be used to update the state. The useState hook
// returns an array with the first element being the state and the second
// element being the function to update the state.

const [users, setUsers] = useState<any[]>([]);

// The useEffect hook basicaly runs the code inside of it when the component
// mounts. This is useful for making API calls and other things that should
// only happen once when the component is loaded.
const [sortAscending, setSortAscending] = useState(true);

useEffect(() => {

// This is an example of an async function. The async keyword tells the
// function to wait for the axios request to finish before continuing. This
// is useful because we can't use the data from the request until it is
// finished.

const getUsers = async () => {

// TODO: Use the apiUrl() function to make a request to the /users endpoint of our USERS service. The first argument is the URL
// of the request, which is created for the hexlabs api through our custom function apiUrl(), which builds the request URL based on
// the Service enum and the following specific endpoint URL.

// TODO: Also explore some of the other ways to configure the api call such as filtering and pagination.
// Try to filter all the users with phone numbers starting with 470 or increase the amount of users returned from the default 50 (don't go above 100).

// Postman will be your best friend here, because it's better to test out the API calls in Postman before implementing them here.

// this is the endpoint you want to hit, but don't just hit it directly using axios, use the apiUrl() function to make the request
const URL = 'https://users.api.hexlabs.org/users/hexlabs';

// uncomment the line below to test if you have successfully made the API call and retrieved the data. The below line takes
// the raw request response and extracts the actual data that we need from it.
// setUsers(data?.data?.profiles);
try {
const response = await axios.get(
apiUrl(Service.USERS, '/users/hexlabs'),
{
params: {
filter: {
phoneNumber: {
$regex: '^470'
}
},
limit: 100
}
}
);
setUsers(response?.data?.profiles || []);
} catch (error) {
console.error('Error fetching users:', error);
}
};

document.title = "Hexlabs Users"
getUsers();
}, []);
// ^^ The empty array at the end of the useEffect hook tells React that the
// hook should only run once when the component is mounted. If you want it to
// run every time a variable changes, you can put that variable in the array
// and it will run every time that variable changes.


// TODO: Create a function that sorts the users array based on the first name of the users. Then, create a button that
// calls this function and sorts the users alphabetically by first name. You can use the built in sort() function to do this.

const handleSort = () => {
const sortedUsers = [...users].sort((a, b) => {
const comparison = a.name.first.localeCompare(b.name.first);
return sortAscending ? comparison : -comparison;
});
setUsers(sortedUsers);
setSortAscending(!sortAscending);
};

return (
<>
<Text fontSize="4xl">Hexlabs Users</Text>
<Text fontSize="2xl">This is an example of a page that makes an API call to the Hexlabs API to get a list of users.</Text>


<HStack spacing={4} padding={4}>
<Button colorScheme="blue" onClick={handleSort}>
Sort by First Name {sortAscending ? '↓' : '↑'}
</Button>
</HStack>

<SimpleGrid columns={[2, 3, 5]} spacing={6} padding={10}>

{/* Here we are mapping every entry in our users array to a unique UserCard component, each with the unique respective
data of each unique user in our array. This is a really important concept that we use a lot so be sure to familiarize
yourself with the syntax - compartmentalizing code makes your work so much more readable. */}
{ users.map((user) => (
<UserCard user={user} />
{users.map((user) => (
<UserCard key={user.userId} user={user} />
))}

</SimpleGrid>
</>
);
Expand Down