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

[Netmanager] Fix displaying users lists #2302

Merged
merged 2 commits into from
Dec 5, 2024
Merged

[Netmanager] Fix displaying users lists #2302

merged 2 commits into from
Dec 5, 2024

Conversation

Codebmk
Copy link
Member

@Codebmk Codebmk commented Dec 5, 2024

Summary of Changes (What does this PR do?)

This pull request includes significant changes to the netmanager project to improve the handling of network users and available users. The changes mainly focus on migrating from local state management to Redux state management and enhancing the user interface for better usability.

State Management Improvements:

User Interface Enhancements:

Component Updates:

Miscellaneous:

  • Removed unused imports and cleaned up code to improve readability and maintainability. [1] [2]

These changes collectively aim to improve the performance, maintainability, and user experience of the netmanager project.

Status of maturity (all need to be checked before merging):

  • I've tested this locally
  • I consider this code done
  • This change ready to hit production in its current state

How should this be manually tested?

  • Please include the steps to be done inorder to setup and test this PR.

What are the relevant tickets?

Screenshots (optional)

image
image

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced loading state management for fetching network users, providing better user feedback during data loading.
    • Updated pagination handling in user lists, allowing users to change rows per page dynamically.
    • Introduced a new table structure for displaying available users, improving customization and readability.
  • Bug Fixes

    • Improved error handling for role summary loading, ensuring clearer error messages.
  • Refactor

    • Transitioned local state management to Redux for user lists, streamlining data handling.
    • Replaced existing table components with Material-UI's table structure for better layout and functionality.
  • Documentation

    • Updated prop types for user table components to reflect new properties related to pagination and user data management.

Copy link

coderabbitai bot commented Dec 5, 2024

📝 Walkthrough

Walkthrough

The changes in this pull request involve modifications to several files in the netmanager/src/redux/AccessControl and netmanager/src/views/pages/UserList directories. Key updates include the removal of the LOAD_ROLES_SUMMARY_FAILURE action, enhancements to loading state management in user fetching functions, and the introduction of new loading indicators in the Redux state. Additionally, the AvailableUserList and UserList components have transitioned from local state management to Redux, improving integration with the application's state. The table components for displaying users have also been revamped to utilize Material-UI's Table components, enhancing customization and functionality.

Changes

File Path Change Summary
netmanager/src/redux/AccessControl/operations.js Removed LOAD_ROLES_SUMMARY_FAILURE; updated fetchNetworkUsers and fetchAvailableNetworkUsers to manage loading states. Modified error handling in loadRolesSummary.
netmanager/src/redux/AccessControl/reducers.js Added loading property to initialState for networkUsers and availableUsers; included cases for SET_NETWORK_USERS_LOADING and SET_AVAILABLE_USERS_LOADING.
netmanager/src/views/pages/UserList/AvailableUserList.js Replaced local state management with Redux; removed fetchUsers; updated pagination handling; modified rendering logic for AvailableUsersTable.
netmanager/src/views/pages/UserList/UserList.js Transitioned to Redux for loading state; integrated loadRolesSummary and fetchNetworkUsers in useEffect; updated pagination handling.
netmanager/src/views/pages/UserList/components/UsersTable/AvailableUsersTable.js Replaced CustomMaterialTable with Material-UI Table components; added pagination controls and updated props for type safety.
netmanager/src/views/pages/UserList/components/UsersTable/UsersTable.js Similar updates as AvailableUsersTable, replacing CustomMaterialTable with Material-UI Table components and enhancing pagination functionality.

Possibly related PRs

Suggested reviewers

  • Baalmart
  • OchiengPaul442

🎉 In the code's dance, a new rhythm plays,
Loading states managed in elegant ways.
Redux takes charge, local states take flight,
User lists shine, all ready and bright!
Material-UI tables now stand tall and grand,
A seamless experience, all perfectly planned! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (10)
netmanager/src/views/pages/UserList/AvailableUserList.js (3)

34-41: Consider adding error handling in the useEffect hook.

Currently, there is no error handling for the fetchAvailableNetworkUsers dispatch within the useEffect hook. Incorporating error handling can improve robustness and user feedback in case of API failures.


43-51: Add error handling in handlePageChange.

Including error handling when dispatching fetchAvailableNetworkUsers will help manage any potential errors during data fetching and enhance user experience.


53-61: Incorporate error handling in handleRowsPerPageChange.

Adding error handling to the dispatch action within handleRowsPerPageChange can prevent unhandled errors and provide better feedback to the user if the fetch operation fails.

netmanager/src/views/pages/UserList/components/UsersTable/AvailableUsersTable.js (3)

Line range hint 74-89: Correct the loading state management in submitEditUser.

The setLoading(false); call immediately after the if block causes the loading state to end before the asynchronous operation completes, which might lead to inconsistent UI behavior. Move setLoading(false); inside the .then and .catch blocks to ensure it reflects the actual loading status.

Apply this diff to fix the issue:

 const submitEditUser = (user) => {
   setLoading(true);
   const userID = user._id;
   // assign user to network
   if (!isEmpty(activeNetwork) && !isEmpty(userID)) {
     assignUserNetworkApi(activeNetwork._id, userID)
       .then((response) => {
         dispatch(fetchAvailableNetworkUsers(activeNetwork._id));
         dispatch(
           updateMainAlert({
             message: 'User successfully added to the organisation. Check in assigned users table',
             show: true,
             severity: 'success'
           })
         );
+        setLoading(false);
       })
       .catch((error) => {
         const errors = error.response && error.response.data && error.response.data.errors;
         dispatch(
           updateMainAlert({
             message: error.response && error.response.data && error.response.data.message,
             show: true,
             severity: 'error',
             extra: createAlertBarExtraContentFromObject(errors || {})
           })
         );
+        setLoading(false);
       });
   }
-  setLoading(false);
 };

193-198: Remove console.log statements from TablePaginationActions.

The console.log statements used for debugging should be removed in the production code to keep the console output clean.

Apply this diff to remove the console.log statements:

 function TablePaginationActions(props) {
   const { count, page, rowsPerPage, onPageChange } = props;
-  console.log('TablePaginationActions props:', {
-    count,
-    page,
-    rowsPerPage,
-    hasOnPageChange: !!onPageChange
-  });

213-219: Eliminate debugging console.log statements from pagination handlers.

Removing the console logs in the pagination handlers will prevent unnecessary clutter in the console output.

Apply this diff:

 const handleNextButtonClick = (event) => {
-  console.log('Next button clicked, current page:', page);
-  console.log('onPageChange exists:', !!onPageChange);
   if (onPageChange) {
-    console.log('Calling onPageChange with:', page + 1);
     onPageChange(event, page + 1);
   }
 };
netmanager/src/views/pages/UserList/components/UsersTable/UsersTable.js (2)

106-113: Remove console.log statements from TablePaginationActions.

The console logs within TablePaginationActions are for debugging and should be removed to maintain a clean console in production environments.

Apply this diff to remove the console.log statements:

 function TablePaginationActions(props) {
   const { count, page, rowsPerPage, onPageChange } = props;
-  console.log('TablePaginationActions props:', {
-    count,
-    page,
-    rowsPerPage,
-    hasOnPageChange: !!onPageChange
-  });

128-134: Delete debugging console.log statements in pagination handlers.

Removing these console logs helps keep the console output clean and avoids potential performance issues.

Apply this diff:

 const handleNextButtonClick = (event) => {
-  console.log('Next button clicked, current page:', page);
-  console.log('onPageChange exists:', !!onPageChange);
   if (onPageChange) {
-    console.log('Calling onPageChange with:', page + 1);
     onPageChange(event, page + 1);
   }
 };
netmanager/src/redux/AccessControl/operations.js (2)

81-81: Consider using action type constants instead of string literals

The loading state management is a good addition, but using string literals for action types ('SET_NETWORK_USERS_LOADING') makes the code more prone to typos and harder to maintain. Consider defining these as constants alongside other action types.

+ // In actions.js
+ export const SET_NETWORK_USERS_LOADING = 'SET_NETWORK_USERS_LOADING';
+ export const SET_AVAILABLE_USERS_LOADING = 'SET_AVAILABLE_USERS_LOADING';

- dispatch({ type: 'SET_NETWORK_USERS_LOADING', payload: true });
+ dispatch({ type: SET_NETWORK_USERS_LOADING, payload: true });

Also applies to: 98-98


104-104: Apply the same action type constant pattern here

For consistency with the previous suggestion, the loading state action type should also be defined as a constant.

- dispatch({ type: 'SET_AVAILABLE_USERS_LOADING', payload: true });
+ dispatch({ type: SET_AVAILABLE_USERS_LOADING, payload: true });

Also applies to: 121-121

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d105038 and 85c68c6.

📒 Files selected for processing (6)
  • netmanager/src/redux/AccessControl/operations.js (3 hunks)
  • netmanager/src/redux/AccessControl/reducers.js (2 hunks)
  • netmanager/src/views/pages/UserList/AvailableUserList.js (2 hunks)
  • netmanager/src/views/pages/UserList/UserList.js (3 hunks)
  • netmanager/src/views/pages/UserList/components/UsersTable/AvailableUsersTable.js (3 hunks)
  • netmanager/src/views/pages/UserList/components/UsersTable/UsersTable.js (4 hunks)
🔇 Additional comments (8)
netmanager/src/views/pages/UserList/AvailableUserList.js (3)

12-12: Importing fetchAvailableNetworkUsers correctly.

The import statement for fetchAvailableNetworkUsers is appropriate and ensures the required action is available for dispatch.


26-27: Initializing pagination state variables.

The page and pageSize state variables are properly initialized using useState, allowing for effective pagination control.


30-31: Utilizing Redux state for users and loading status.

Accessing users, total, and loading from the Redux store with useSelector enhances state management consistency across the application.

netmanager/src/views/pages/UserList/UserList.js (3)

15-15: Successfully importing fetchNetworkUsers.

The import statement ensures that the fetchNetworkUsers action is available for dispatch, aligning the component with the Redux action flow.


29-30: Initializing pagination control state variables.

The page and pageSize state variables are correctly initialized, setting up the component for effective pagination management.


33-33: Accessing users and loading state from Redux store.

Using useSelector to retrieve users, total, and loading from the Redux state ensures consistent data and loading status throughout the application.

netmanager/src/redux/AccessControl/operations.js (2)

Line range hint 89-97: Well-implemented error handling pattern

The error handling implementation is robust and follows best practices:

  • Dispatches failure actions for Redux state updates
  • Rethrows errors for component-level handling
  • Uses finally block to guarantee loading state reset

Also applies to: 112-120


Line range hint 81-98: Verify reducer handling of loading states

Let's verify that the reducer properly handles these new loading state actions.

Also applies to: 104-121

✅ Verification successful

Loading state actions are properly handled in the reducer

The reducer correctly handles the SET_NETWORK_USERS_LOADING action by:

  • Maintaining the loading state in networkUsers.loading
  • Preserving other state properties during updates
  • Having proper initial state with loading: false
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the corresponding reducer cases
ast-grep --pattern 'case $ACTION_TYPE: {
  $$$
  loading: $$$
  $$$
}'

# Also check for the initial state definition
rg -A 5 'initialState.*=.*{' netmanager/src/redux/AccessControl/reducers.js

Length of output: 250


Script:

#!/bin/bash
# Search for the reducer file content
cat netmanager/src/redux/AccessControl/reducers.js

# Alternatively, search for loading state related cases
rg "SET_NETWORK_USERS_LOADING" netmanager/src/redux/AccessControl/

Length of output: 2531

Comment on lines 38 to +50
if (!activeNetwork) return;
dispatch(loadRolesSummary(activeNetwork._id));
}, []);

const fetchUsers = async (skipCount, limitCount) => {
if (!activeNetwork) return;
setLoading(true);
try {
const res = await getNetworkUsersListApi(activeNetwork._id, {
skip: skipCount,
limit: limitCount
});
setUsers(res.assigned_users);
setTotalCount(res.total || 0);
dispatch(loadRolesSummary(activeNetwork._id));
dispatch(
fetchNetworkUsers(activeNetwork._id, {
skip: page * pageSize,
limit: pageSize
})
);
} catch (error) {
let errorMessage = 'An error occurred';
if (error.response && error.response.status >= 500) {
errorMessage = 'An error occurred. Please try again later';
} else if (error.response && error.response.data && error.response.data.message) {
errorMessage = error.response.data.message;
} else if (error.message) {
errorMessage = error.message;
}
console.error('Error fetching network users:', error);
}
}, [activeNetwork]);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Reevaluate error handling in the useEffect hook.

Wrapping dispatch calls in a try-catch block may not effectively handle asynchronous errors from Redux actions. It's better to handle errors within the action creators or use middleware like Redux Thunk or Redux Saga for async operations.

Comment on lines +52 to +62
const handlePageChange = (event, newPage) => {
setPage(newPage);
try {
dispatch(
updateMainAlert({
message: errorMessage,
show: true,
severity: 'error'
fetchNetworkUsers(activeNetwork._id, {
skip: newPage * pageSize,
limit: pageSize
})
);
} finally {
setLoading(false);
} catch (error) {
console.error('Error fetching network users:', error);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Adjust error handling in handlePageChange.

The try-catch block may not catch errors from asynchronous dispatch operations. Consider managing errors within the fetchNetworkUsers action or utilizing middleware to handle async actions properly.

Comment on lines +66 to +78
const handleRowsPerPageChange = (newPageSize) => {
setPageSize(newPageSize);
setPage(0);
try {
dispatch(
fetchNetworkUsers(activeNetwork._id, {
skip: 0,
limit: newPageSize
})
);
} catch (error) {
console.error('Error fetching network users:', error);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve error handling in handleRowsPerPageChange.

Similar to other dispatch calls, the current error handling may not be effective for asynchronous actions. Handling errors within the action creator or middleware can provide more reliable error management.

Comment on lines +62 to +77
case 'SET_NETWORK_USERS_LOADING':
return {
...state,
networkUsers: {
...state.networkUsers,
loading: action.payload
}
};
case 'SET_AVAILABLE_USERS_LOADING':
return {
...state,
availableUsers: {
...state.availableUsers,
loading: action.payload
}
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Define action types as constants for consistency.

Currently, 'SET_NETWORK_USERS_LOADING' and 'SET_AVAILABLE_USERS_LOADING' are string literals. Defining them as constants in the actions.js file enhances code maintainability and reduces the risk of typos.

Apply this diff:

In actions.js:

+export const SET_NETWORK_USERS_LOADING = 'SET_NETWORK_USERS_LOADING';
+export const SET_AVAILABLE_USERS_LOADING = 'SET_AVAILABLE_USERS_LOADING';

In reducers.js:

 import {
   ASSIGN_USER_TO_NETWORK_SUCCESS,
   LOAD_ALL_USER_ROLES_SUCCESS,
   LOAD_AVAILABLE_USERS_SUCCESS,
   LOAD_CURRENT_NETWORK_SUCCESS,
   LOAD_CURRENT_USER_NETWORKS_SUCCESS,
   LOAD_CURRENT_USER_ROLE_SUCCESS,
   LOAD_GROUPS_SUMMARY_SUCCESS,
   LOAD_NETWORK_USERS_SUCCESS,
   LOAD_ROLES_SUMMARY_SUCCESS,
+  SET_NETWORK_USERS_LOADING,
+  SET_AVAILABLE_USERS_LOADING
 } from './actions';

 // ...

-    case 'SET_NETWORK_USERS_LOADING':
+    case SET_NETWORK_USERS_LOADING:
       return {
         ...state,
         networkUsers: {
           ...state.networkUsers,
           loading: action.payload
         }
       };
-    case 'SET_AVAILABLE_USERS_LOADING':
+    case SET_AVAILABLE_USERS_LOADING:
       return {
         ...state,
         availableUsers: {
           ...state.availableUsers,
           loading: action.payload
         }
       };

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Contributor

github-actions bot commented Dec 5, 2024

New netmanager changes available for preview here

@Baalmart Baalmart merged commit b267c07 into staging Dec 5, 2024
31 checks passed
@Baalmart Baalmart deleted the ft-table-listing branch December 5, 2024 15:53
@Codebmk Codebmk mentioned this pull request Dec 5, 2024
1 task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants