Explore / Programming import React, { useState, useEffect } from 'react'; import { useRouter } from… Save Share Download ▾ Reportimport React, { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import { makeStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import School from "@material-ui/icons/School";
import PermIdentity from '@material-ui/icons/PermIdentity';
import Description from '@material-ui/icons/Description';
import Work from "@material-ui/icons/Work";
import Code from "@material-ui/icons/Code";
import GitHub from "@material-ui/icons/GitHub";
import GridContainer from "/components/Grid/GridContainer.js";
import GridItem from "/components/Grid/GridItem.js";
import CustomTabs from "/components/CustomTabs/CustomTabs.js";
import styles from "/styles/jss/nextjs-material-kit/pages/componentsSections/tabsStyle.js";
import Education from '../../components/Profile/Education';
import Experience from '../../components/Profile/Experience';
import Leetcode from '../../components/Profile/Leetcode';
import Github from '../../components/Profile/Github';
import Extras from '../../components/Profile/Extras';
import { getServerAuthSession } from "../../lib/auth";
import { fetchUserProfile, updateUserProfile, getVerifiedUser } from '../../utils/api';
import CustomLinearProgress from "/components/CustomLinearProgress/CustomLinearProgress.js";
import BasicInfo from '../../components/Profile/BasicInfo';
const useStyles = makeStyles(styles);
const defaultProfileData = {
basicInfo: {
name: '',
email: '',
universityEmail: '',
phone: '',
city: '',
minimumSalary: 60000,
international: '',
countryOfOrigin: '',
relocationWillingness: '', // Added Relocation
gpa: '', // Added GPA
linkedinUrl: '', // Added LinkedIn URL
twitterUrl: '', // Added Twitter URL
jobType: '',
},
educations: [{ university: '', universityLocation: '', degree: '', fieldOfStudy: '', yearFrom: '', yearTo: '' }],
experiences: [{
type: '',
title: '',
company: '',
startDate: '',
endDate: '',
techStack: '',
linkedinUrl: '',
// tier: 0,
points: [{ what: '', impact: '' }]
}],
leetcode: { username: '', userData: null },
github: {
stars: '',
username: '',
projects: [{
type: '',
name: '',
role: '',
githubUrl: '',
startDate: '',
endDate: '',
techStack: '',
points: [{ what: '', impact: '' }, { what: '', impact: '' }]
}]
},
};
const tier1Companies = [
'Google', 'Amazon', 'Facebook (Meta)', 'Apple', 'Microsoft', 'Netflix',
'OpenAI', 'DeepMind', 'Anthropic', 'Nvidia', 'Tesla', 'SpaceX',
'Stripe', 'Shopify', 'Salesforce', 'Airbnb', 'Uber', 'Lyft',
'Palantir', 'Databricks', 'Snowflake', 'Zoom', 'Slack', 'Dropbox',
'Doordash', 'Instacart', 'Robinhood', 'Coinbase', 'Brex', 'Asana',
'HubSpot', 'Atlassian', 'Adobe', 'Splunk', 'Twilio',
'Citadel', 'Jane Street', 'Hudson River Trading',
'Renaissance Technologies', 'D.E. Shaw', 'Two Sigma', 'Jump Trading'
];
// Tier 2 Companies (Well-known Tech & Non-Tech):
const tier2Companies = [
'Square', 'Pinterest', 'Spotify', 'Reddit', 'Cloudflare', 'Okta', 'MongoDB',
'Twilio', 'Shopify', 'DocuSign', 'ServiceNow', 'Workday',
'Qualcomm', 'Intel', 'AMD', 'Broadcom', 'Marvell',
'Goldman Sachs', 'JPMorgan Chase', 'Morgan Stanley',
'McKinsey & Company', 'Boston Consulting Group', 'Bain & Company',
'Accenture', 'Deloitte', 'PwC', 'EY',
'Bell Canada', 'Rogers Communications', 'Telus',
'Canadian National Railway', 'Enbridge', 'TD Bank',
'Royal Bank of Canada', 'Bank of Montreal', 'Scotiabank'
];
Show full message · 641 lines Assistant2024-09-20 20:45 UTC Copy response
The issue stems from how your isTabComplete function handles arrays, especially empty arrays like the points array within your experiences. Currently, your isTabComplete function doesn't check if arrays are empty; it only checks if they exist. This means that even if the points array is empty (which it shouldn't be for a complete experience), your function considers it complete.
However, when you save and reload the data from the backend, the array might be populated with defaults or the backend might have logic to prevent empty arrays, making it appear complete upon reload.
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Sep 20, 2024
Added to archive Nov 16, 2026
ID 01m7h41vbjn9sd1y7x5hxwhjmpSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 9a420d51ef0619555ec195d42151aa32
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
// Tier 3 Companies (Still Well-Known, Maybe Not as Highly Paid)
const tier3Companies = [
'CIBC', 'Desjardins Group', 'Manulife', 'Sun Life Financial',
'Great-West Lifeco', 'Power Corporation of Canada', 'Hydro-Québec',
'BCE Inc.', 'Loblaw Companies', 'George Weston Limited',
'Magna International', 'Bombardier', 'SNC-Lavalin', 'CGI Inc.',
'Imperial Oil', 'Canadian Natural Resources', 'Cenovus Energy',
'Suncor Energy', 'Teck Resources', 'Barrick Gold',
'Agnico Eagle Mines', 'Kinross Gold', 'First Quantum Minerals'
];
const CACHE_KEY = 'user_profile_cache';
const getCachedProfile = () => {
if (typeof window !== 'undefined') {
const cachedData = localStorage.getItem(CACHE_KEY);
return cachedData ? JSON.parse(cachedData) : null;
}
return null;
};
const setCachedProfile = (data) => {
if (typeof window !== 'undefined') {
localStorage.setItem(CACHE_KEY, JSON.stringify(data));
}
};
export default function Profile({ serverSession }) {
const router = useRouter();
const classes = useStyles();
const [profileData, setProfileData] = useState(defaultProfileData);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [completionPercentage, setCompletionPercentage] = useState(0);
const [incompleteTabsMap, setIncompleteTabsMap] = useState({});
useEffect(() => {
if (!serverSession) {
router.push('/login');
} else {
const cachedData = getCachedProfile();
if (cachedData) {
setProfileData(cachedData);
setLoading(false);
}
fetchProfileData();
}
}, [serverSession, router]);
useEffect(() => {
const percentage = calculateCompletionPercentage(profileData);
setCompletionPercentage(percentage);
updateIncompleteTabsMap(profileData);
}, [profileData]);
const fetchProfileData = async () => {
try {
const data = await fetchUserProfile(serverSession.user.id);
setProfileData(data);
setCachedProfile(data);
} catch (err) {
console.error('Error fetching profile:', err);
setError('Failed to load profile data. Using cached or default profile.');
if (!getCachedProfile()) {
setProfileData(defaultProfileData);
}
} finally {
setLoading(false);
}
};
const handleSave = async () => {
try {
const verifieduser = await getVerifiedUser(serverSession.user.id);
const emailVerified = verifieduser.emailVerified;
const dataToSave = {
...profileData,
completionPercentage: completionPercentage,
emailVerified: emailVerified
};
const updatedProfile = await updateUserProfile(dataToSave);
code Copy code
setCachedProfile(updatedProfile);
// Handle successful save (e.g., show a success message)
} catch (error) {
console.error('Error saving profile:', error);
// Handle error (e.g., show an error message to the user)
}
const handleEducationChange = (index, event) => {
setProfileData(prevState => ({
...prevState,
educations: prevState.educations.map((education, i) =>
i === index ? { ...education, [event.target.name]: event.target.value } : education
),
}));
};
const addEducation = (event) => {
event.preventDefault();
if (profileData.educations.length < 3) {
setProfileData(prevState => ({
...prevState,
educations: [
...prevState.educations,
{ university: '', universityLocation: '', degree: '', fieldOfStudy: '', yearFrom: '', yearTo: '' },
],
}));
}
};
const handleExperienceChange = (index, field, value) => {
setProfileData(prevState => ({
...prevState,
experiences: prevState.experiences.map((experience, i) =>
i === index
? {
...experience,
[field]: value,
// Only update tier if the field being changed is 'company'
...(field === 'company' ? { tier: getCompanyTier(value) } : {})
}
: experience
),
}));
};
const getCompanyTier = (company) => {
// If company is undefined or null, return 0 (default tier)
if (!company) {
return 0;
}
code Copy code
const lowerCaseCompany = company.toLowerCase();
if (tier1Companies.some(tier1Company => tier1Company.toLowerCase().includes(lowerCaseCompany))) {
return 1;
} else if (tier2Companies.some(tier2Company => tier2Company.toLowerCase().includes(lowerCaseCompany))) {
return 2;
} else if (tier3Companies.some(tier3Company => tier3Company.toLowerCase().includes(lowerCaseCompany))) {
return 3;
}
return 0;
const handleTechStackChange = (index, event) => {
const techStack = event.target.value
.split(',')
.map(tech => tech.trim().charAt(0).toUpperCase() + tech.trim().slice(1))
.join(', ');
code Copy code
handleExperienceChange(index, 'techStack', techStack);
const handlePointChange = (experienceIndex, pointIndex, field, value) => {
setProfileData(prevState => ({
...prevState,
experiences: prevState.experiences.map((experience, i) =>
i === experienceIndex
? {
...experience,
points: experience.points.map((point, j) =>
j === pointIndex ? { ...point, [field]: value } : point
),
}
: experience
),
}));
};
const addExperience = (event) => {
event.preventDefault();
if (profileData.experiences.length < 8) {
setProfileData(prevState => ({
...prevState,
experiences: [
...prevState.experiences,
{ type: '', title: '', company: '', startDate: '', endDate: '', techStack: '', points: [{ what: '', impact: '' }] },
],
}));
}
};
const handleUsernameChange = (event) => {
setProfileData(prevState => ({
...prevState,
leetcode: {
...prevState.leetcode,
username: event.target.value,
},
}));
setError(null);
};
const fetchUserData = async (event) => {
event.preventDefault();
try {
const response = await fetch(/api/leetcode-user?username=${encodeURIComponent(profileData.leetcode.username)});
if (!response.ok) {
throw new Error('Failed to fetch user data');
}
const data = await response.json();
setProfileData(prevState => ({
...prevState,
leetcode: {
...prevState.leetcode,
userData: data,
},
}));
} catch (err) {
setError('Failed to fetch user data. Please check the username and try again.');
}
};
const applyRedHotShadow = (userData) => {
if (!userData) return false;
const totalSolved = userData.submitStats.acSubmissionNum.reduce((acc, stat) => acc + stat.count, 0);
const contestRating = userData.userContestRanking ? userData.userContestRanking.rating : 0;
const activeYears = userData.userCalendar.activeYears.length;
const totalActiveDays = userData.userCalendar.totalActiveDays;
code Copy code
return (
totalSolved > 700 ||
(contestRating > 1850 && (activeYears > 1 || totalActiveDays > 100)) ||
(contestRating > 1850 && totalActiveDays > 150)
);
const handleGithubChange = (event) => {
setProfileData(prevState => ({
...prevState,
github: {
...prevState.github,
[event.target.name]: event.target.value,
},
}));
};
const handleProjectChange = (index, field, value) => {
setProfileData(prevState => ({
...prevState,
github: {
...prevState.github,
projects: prevState.github.projects.map((project, i) =>
i === index ? { ...project, [field]: value } : project
),
},
}));
};
const handleProjectTechStackChange = (index, event) => {
const techStack = event.target.value
.split(',')
.map(tech => tech.trim().charAt(0).toUpperCase() + tech.trim().slice(1))
.join(', ');
code Copy code
handleProjectChange(index, 'techStack', techStack);
const addProject = (event) => {
event.preventDefault();
if (profileData.github.projects.length < 3) {
setProfileData(prevState => ({
...prevState,
github: {
...prevState.github,
projects: [
...prevState.github.projects,
{
type: '',
name: '',
role: '',
githubUrl: '',
startDate: '',
endDate: '',
techStack: '',
points: [{ what: '', impact: '' }, { what: '', impact: '' }]
},
],
},
}));
}
};
const handleBasicInfoChange = (event) => {
setProfileData(prevState => ({
...prevState,
basicInfo: {
...prevState.basicInfo,
[event.target.name]: event.target.value,
},
}));
};
const handleSalarySliderChange = (values) => {
setProfileData(prevState => ({
...prevState,
basicInfo: {
...prevState.basicInfo,
minimumSalary: Math.round(values[0]),
},
}));
};
const handleBasicDetailsChange = (event) => {
setProfileData(prevState => ({
...prevState,
basicInfo: {
...prevState.basicInfo,
[event.target.name]: event.target.value,
},
}));
};
const renderTabContent = (TabComponent, props) => {
if (loading) {
return Loading...;
}
return <TabComponent {...props} />;
};
const calculateCompletionPercentage = (data) => {
let totalFields = 0;
let filledFields = 0;
code Copy code
const countFields = (obj) => {
for (const key in obj) {
if (key === 'twitterUrl') continue; // Skip twitterUrl
if (key === 'countryOfOrigin' && obj['international'] === 'no') continue; // Skip countryOfOrigin if not international
if (key === 'tier') continue;
if (typeof obj[key] === 'object' && obj[key] !== null) {
countFields(obj[key]);
} else {
totalFields++;
if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
filledFields++;
}
}
}
};
countFields(data);
return totalFields > 0 ? (filledFields / totalFields) * 100 : 0;
const updateIncompleteTabsMap = (data) => {
const newIncompleteTabsMap = {
basicInfo: !isTabComplete(data.basicInfo),
education: !isTabComplete(data.educations),
experience: !isTabComplete(data.experiences),
leetcode: !isTabComplete(data.leetcode),
github: !isTabComplete(data.github),
extras: !isTabComplete(data.basicInfo, ['gpa', 'linkedinUrl', 'twitterUrl','jobType'])
};
setIncompleteTabsMap(newIncompleteTabsMap);
// Log the experience tab status and the experiences data
console.log('Experience Tab Incomplete:', newIncompleteTabsMap.experience);
const isTabComplete = (data, fields = null) => {
if (Array.isArray(data)) {
return data.every(item => isTabComplete(item));
}
if (typeof data === 'object' && data !== null) {
const keysToCheck = fields || Object.keys(data);
return keysToCheck.every(key => {
const value = data[key];
console.log(Checking field: ${key}, Value: ${value}); // Log each field being checked
return value !== '' && value !== null && value !== undefined;
});
}
return false;
};
const customTabStyle = (tabName) => {
return incompleteTabsMap[tabName]
? {
borderBottom: '2px solid red',
color: 'red !important', // Override the default white color
fontWeight: 'bold' // Make incomplete tabs stand out more
}
: {};
};
return (
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
Your Profile
<Button
variant="contained"
color="secondary"
onClick={() => router.push('/v1/card')}
style={{ marginRight: '10px' }}
>
Anonymous Card
<Button
variant="contained"
color="primary"
onClick={handleSave}
style={{ backgroundColor: 'green', color: 'white' }}
>
Save
{error && <p style={{color: 'red'}}>{error}}
code Copy code
<CustomLinearProgress
variant="determinate"
color="primary"
value={completionPercentage}
/>
<p>Profile Completion: {completionPercentage.toFixed(2)}%</p>
<GridContainer>
<GridItem xs={12} sm={12} md={12}>
<CustomTabs
headerColor="primary"
tabs={[
{
tabName: "Basic Info",
tabIcon: PermIdentity,
tabContent: renderTabContent(BasicInfo, {
basicInfo: profileData.basicInfo,
handleBasicInfoChange,
handleSalarySliderChange,
handleBasicDetailsChange,
}),
tabStyle: customTabStyle('basicInfo'),
},
{
tabName: "Education",
tabIcon: School,
tabContent: renderTabContent(Education, {
educations: profileData.educations,
handleEducationChange,
addEducation,
}),
tabStyle: customTabStyle('education'),
},
{
tabName: "Experience",
tabIcon: Work,
tabContent: renderTabContent(Experience, {
experiences: profileData.experiences,
handleExperienceChange,
addExperience,
handleTechStackChange,
handlePointChange,
}),
tabStyle: customTabStyle('experience'),
},
{
tabName: "Leetcode",
tabIcon: Code,
tabContent: renderTabContent(Leetcode, {
username: profileData.leetcode.username,
userData: profileData.leetcode.userData,
handleUsernameChange,
fetchUserData,
applyRedHotShadow,
}),
tabStyle: customTabStyle('leetcode'),
},
{
tabName: "GitHub",
tabIcon: GitHub,
tabContent: renderTabContent(Github, {
github: profileData.github,
handleGithubChange,
handleProjectChange,
addProject,
projects: profileData.github.projects,
handleProjectTechStackChange,
}),
tabStyle: customTabStyle('github'),
},
{
tabName: "Screening",
tabIcon: Description,
tabContent: renderTabContent(Extras, {
basicInfo: profileData.basicInfo,
handleBasicDetailsChange,
}),
tabStyle: customTabStyle('extras'),
},
]}
/>
</GridItem>
</GridContainer>
</div>
</div>
</div>
export async function getServerSideProps(context) {
const session = await getServerAuthSession(context);
if (!session) {
return {
redirect: {
destination: '/login',
permanent: false,
},
};
}
// Ensure the role is defined or set to null
const role = session.user.role || null;
if (!role || session.user.role === 'recruiter') {
return {
redirect: {
destination: '/v1/verify',
permanent: false,
},
};
}
return {
props: {
serverSession: session,
},
};
}
Experience completition calculation is messed up.
Even if experience is complete, it still says it's incomplete. However, when I save it and then refresh page(which fetches the same saved data from backend), now it says its complete.
Checking field: points, Value: [object Object],[object Object],[object Object]
profile.js:472 Checking field: [object Object], Value: undefined
This is from the logs. Initially I thought tier is the culprit, but I commented it out.
points
To fix this, you need to modify your isTabComplete function to consider empty arrays as incomplete. Here's how you can adjust your function:
javascript Copy code
const isTabComplete = (data, fields = null) => {
if (Array.isArray(data)) {
if (data.length === 0) {
return false; // Empty array is incomplete
}
return data.every(item => isTabComplete(item));
}
if (typeof data === 'object' && data !== null) {
const keysToCheck = fields || Object.keys(data);
return keysToCheck.every(key => {
if (key === 'tier') return true; // Skip 'tier' if it causes issues
const value = data[key];
if (value !== '' && value !== null && value !== undefined) {
if (typeof value === 'object') {
return isTabComplete(value);
} else {
return true;
}
} else {
return false;
}
});
}
return false;
};
By adding the check if (data.length === 0) { return false; }, you're ensuring that empty arrays (like an empty points array in an experience) cause the function to return false, marking the tab as incomplete. This change ensures that all nested fields, including objects and arrays, are fully checked for completeness.
This modification should resolve the issue where the Experience tab is incorrectly marked as incomplete when all fields are filled.
Copy first response
Not yet included in a published release.