Skip to content

Commit

Permalink
Enhancements on JSON errors
Browse files Browse the repository at this point in the history
  • Loading branch information
OchiengPaul442 committed Mar 8, 2025
1 parent 280275e commit 208229e
Show file tree
Hide file tree
Showing 11 changed files with 579 additions and 251 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,39 @@ const OrganizationDropdown = () => {

// Initialize active group if missing
useEffect(() => {
// If we're still fetching, do nothing yet
if (isFetchingActiveGroup) return;

const storedGroup = localStorage.getItem('activeGroup');
if (storedGroup) {
const defaultGroup = JSON.parse(storedGroup);
dispatch(setOrganizationName(defaultGroup.grp_title));
try {
// Attempt to parse the stored group
const defaultGroup = JSON.parse(storedGroup);

// Check if defaultGroup and its properties exist
if (defaultGroup && defaultGroup.grp_title) {
dispatch(setOrganizationName(defaultGroup.grp_title));
} else {
// If the stored data is missing expected fields, remove it
localStorage.removeItem('activeGroup');
console.warn(
'activeGroup in localStorage is missing grp_title, removing it...',
);
}
} catch (error) {
// If JSON parsing fails, remove the invalid item
console.error('Error parsing activeGroup from localStorage:', error);
localStorage.removeItem('activeGroup');
}
} else if (!activeGroupId && activeGroups.length > 0) {
// No activeGroup in localStorage, so pick the first available group
const defaultGroup = activeGroups[0];
localStorage.setItem('activeGroup', JSON.stringify(defaultGroup));
dispatch(setOrganizationName(defaultGroup.grp_title));
if (defaultGroup && defaultGroup.grp_title) {
dispatch(setOrganizationName(defaultGroup.grp_title));
}
}
}, [activeGroupId, activeGroups, dispatch]);
}, [isFetchingActiveGroup, activeGroupId, activeGroups, dispatch]);

const handleUpdatePreferences = useCallback(
async (group) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,18 @@ const AddLocations = ({ onClose }) => {

// Retrieve user ID from localStorage and memoize it
const userID = useMemo(() => {
const user = localStorage.getItem('loggedUser');
return user ? JSON.parse(user)?._id : null;
const storedUser = localStorage.getItem('loggedUser');
if (!storedUser) {
return null;
}

try {
const parsedUser = JSON.parse(storedUser);
return parsedUser?._id ?? null;
} catch (error) {
console.error('Error parsing loggedUser from localStorage:', error);
return null;
}
}, []);

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,18 @@ const SelectMore = ({ onClose }) => {

// Retrieve user ID from localStorage and memoize it
const userID = useMemo(() => {
const user = localStorage.getItem('loggedUser');
return user ? JSON.parse(user)?._id : null;
const storedUser = localStorage.getItem('loggedUser');
if (!storedUser) {
return null;
}

try {
const parsedUser = JSON.parse(storedUser);
return parsedUser?._id ?? null;
} catch (error) {
console.error('Error parsing "loggedUser" from localStorage:', error);
return null;
}
}, []);

// Extract selected site IDs from user preferences
Expand Down
100 changes: 70 additions & 30 deletions src/platform/src/common/components/Settings/Teams/InviteForm.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ const TeamInviteForm = ({ open, closeModal }) => {
const handleSubmit = (e) => {
e.preventDefault();

if (emails[0] === '') {
// Basic validation: check if the first email input is empty
if (!emails[0]) {
setIsError({
isError: true,
message: 'Please enter an email',
Expand All @@ -71,45 +72,84 @@ const TeamInviteForm = ({ open, closeModal }) => {
}

setLoading(true);

// Check if all emails are valid
const isValid = emails.every((email) => isValidEmail(email));

if (isValid) {
// Safely retrieve and parse 'activeGroup' from localStorage
const storedActiveGroup = localStorage.getItem('activeGroup');
if (!storedActiveGroup) {
// If it's not found, handle accordingly
setIsError({
isError: true,
message: 'No active group found in localStorage',
type: 'error',
});
setLoading(false);
return;
}

let activeGroup;
try {
const activeGroup = JSON.parse(localStorage.getItem('activeGroup'));
if (!activeGroup) {
throw new Error('No active group found');
}
inviteUserToGroupTeam(activeGroup._id, emails)
.then((response) => {
setIsError({
isError: true,
message: response.message,
type: 'success',
});

setTimeout(() => {
setLoading(false);
setEmails(['']);
setEmailErrors([]);
closeModal();
}, 3000);
})
.catch((error) => {
setIsError({
isError: true,
message: error?.response?.data?.errors?.message,
type: 'error',
});
setLoading(false);
});
activeGroup = JSON.parse(storedActiveGroup);
} catch (error) {
console.error(error);
console.error('Error parsing "activeGroup" from localStorage:', error);
setIsError({
isError: true,
message: 'Invalid data in localStorage for "activeGroup"',
type: 'error',
});
// Optionally remove the invalid item to prevent repeated errors
// localStorage.removeItem('activeGroup');
setLoading(false);
return;
}

if (!activeGroup || !activeGroup._id) {
setIsError({
isError: true,
message: 'No valid active group found',
type: 'error',
});
setLoading(false);
return;
}

// Proceed with your invite action
inviteUserToGroupTeam(activeGroup._id, emails)
.then((response) => {
setIsError({
isError: true,
message: response.message,
type: 'success',
});

setTimeout(() => {
setLoading(false);
setEmails(['']);
setEmailErrors([]);
closeModal();
}, 3000);
})
.catch((error) => {
setIsError({
isError: true,
message:
error?.response?.data?.errors?.message || 'Something went wrong',
type: 'error',
});
setLoading(false);
});
} else {
// Display an error message or handle invalid emails
// Handle invalid emails
setLoading(false);
console.log('Invalid emails:', emailErrors);
setIsError({
isError: true,
message: 'One or more emails are invalid',
type: 'error',
});
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,27 @@ const AuthenticatedSideBar = () => {
const collocationOpenState = localStorage.getItem('collocationOpen');
const analyticsOpenState = localStorage.getItem('analyticsOpen');

if (collocationOpenState)
setCollocationOpen(JSON.parse(collocationOpenState));
if (analyticsOpenState) setAnalyticsOpen(JSON.parse(analyticsOpenState));
if (collocationOpenState) {
try {
setCollocationOpen(JSON.parse(collocationOpenState));
} catch (error) {
console.error(
'Error parsing "collocationOpen" from localStorage:',
error,
);
}
}

if (analyticsOpenState) {
try {
setAnalyticsOpen(JSON.parse(analyticsOpenState));
} catch (error) {
console.error(
'Error parsing "analyticsOpen" from localStorage:',
error,
);
}
}
}, []);

// Save dropdown states to localStorage
Expand Down
18 changes: 15 additions & 3 deletions src/platform/src/common/components/SideBar/SideBarDrawer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,21 @@ const SideBarDrawer = () => {
const router = useRouter();
const userInfo = useSelector((state) => state.login.userInfo);
const [isLoading, setIsLoading] = useState(false);
const [collocationOpen, setCollocationOpen] = useState(() =>
JSON.parse(localStorage.getItem('collocationOpen') || 'false'),
);
const [collocationOpen, setCollocationOpen] = useState(() => {
try {
const storedValue = localStorage.getItem('collocationOpen');
if (!storedValue || storedValue === 'undefined') {
return false;
}
return JSON.parse(storedValue);
} catch (error) {
console.error(
'Error parsing "collocationOpen" from localStorage:',
error,
);
return false;
}
});

const drawerClasses = useMemo(
() => (togglingDrawer ? 'w-72' : 'w-0'),
Expand Down
30 changes: 24 additions & 6 deletions src/platform/src/core/utils/protectedRoute.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,20 @@ export const withPermission = (Component, requiredPermission) => {
useEffect(() => {
if (typeof window !== 'undefined') {
const storedUserGroup = localStorage.getItem('activeGroup');
const parsedUserGroup = storedUserGroup
? JSON.parse(storedUserGroup)
: {};
const currentRole = parsedUserGroup?.role;
let parsedUserGroup = {};

if (storedUserGroup) {
try {
parsedUserGroup = JSON.parse(storedUserGroup);
} catch (error) {
console.error(
'Error parsing "activeGroup" from localStorage:',
error,
);
}
}

const currentRole = parsedUserGroup?.role;
const hasPermission = currentRole?.role_permissions?.some(
(permission) => permission.permission === requiredPermission,
);
Expand All @@ -57,13 +66,22 @@ export const withPermission = (Component, requiredPermission) => {
export const checkAccess = (requiredPermission) => {
if (requiredPermission && typeof window !== 'undefined') {
const storedGroupObj = localStorage.getItem('activeGroup');
const currentRole = storedGroupObj ? JSON.parse(storedGroupObj).role : null;
let currentRole = null;

if (storedGroupObj) {
try {
const parsedGroup = JSON.parse(storedGroupObj);
currentRole = parsedGroup?.role || null;
} catch (error) {
console.error('Error parsing "activeGroup" from localStorage:', error);
}
}

const permissions = currentRole?.role_permissions?.map(
(item) => item.permission,
);

return permissions?.includes(requiredPermission) ?? false;
}

return false;
};
35 changes: 23 additions & 12 deletions src/platform/src/pages/Home/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,28 @@ const createSteps = (handleModal, handleCardClick) => [
},
];

const useUserData = () => {
const userData = useMemo(() => {
if (typeof window === 'undefined') {
return null;
}

const storedUser = localStorage.getItem('loggedUser');
if (!storedUser || storedUser === 'undefined') {
return null;
}

try {
return JSON.parse(storedUser);
} catch (error) {
console.error('Error parsing "loggedUser" from localStorage:', error);
return null;
}
}, []);

return userData;
};

const Home = () => {
const dispatch = useDispatch();

Expand All @@ -72,18 +94,7 @@ const Home = () => {
const totalSteps = 4;

// Safely retrieve user data from localStorage
const userData = useMemo(() => {
if (typeof window !== 'undefined') {
const storedUser = localStorage.getItem('loggedUser');
try {
return storedUser ? JSON.parse(storedUser) : null;
} catch (error) {
console.error('Error parsing user data from localStorage:', error);
return null;
}
}
return null;
}, []);
const userData = useUserData();

// Handlers
const handleModal = useCallback(() => {
Expand Down
Loading

0 comments on commit 208229e

Please sign in to comment.