Skip to content

Issueid #236586 feat: migrate localstorage values to redux store#300

Open
ajinkyapandetekdi wants to merge 6 commits intoSunbird-ALL:all-1.4.0from
ajinkyapandetekdi:17-march-all-1.4.0
Open

Issueid #236586 feat: migrate localstorage values to redux store#300
ajinkyapandetekdi wants to merge 6 commits intoSunbird-ALL:all-1.4.0from
ajinkyapandetekdi:17-march-all-1.4.0

Conversation

@ajinkyapandetekdi
Copy link
Copy Markdown
Contributor

@ajinkyapandetekdi ajinkyapandetekdi commented Mar 18, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced user experience with centralized state management, ensuring consistent handling of authentication, language preferences, and progress tracking.
    • Improved telemetry and event tracking by incorporating real-time user data, resulting in more accurate analytics.
  • Refactor

    • Streamlined data flows across the application by replacing local storage methods with a robust state-driven approach, enhancing overall consistency and security.
    • Introduced Redux for managing user journey data, improving the flow of user-specific information across various components.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 18, 2025

Walkthrough

This pull request transitions multiple parts of the application from local storage–based state management to a centralized Redux approach for managing user journey data. In various UI components, API services, and telemetry functions, data such as language, token, session IDs, and milestone details are now obtained from the Redux store. Function signatures across several services have been updated to accept additional parameters. A new Redux slice for user journey management has been created and integrated into the store, with the TOKEN assignment and helper utilities also modified.

Changes

File(s) Change Summary
src/App.js, src/components/{Assesment/*.jsx, Discover*/**.jsx, Layouts.jsx/MainLayout.jsx, Practice/Mechanics*.jsx}, src/views/{LoginPage.jsx, Practice.jsx, AppContent.jsx}, src/utils/VoiceAnalyser.js, src/utils/constants.js Refactored UI components to replace local storage access with Redux state management (using useSelector and dispatching actions) for user journey data (language, token, session, milestone).
src/services/{callTelemetryIntract.js, content/contentService.js, learnerAi/learnerAiService.js, orchestration/orchestrationService.js, telementryService.js} Updated function signatures and header construction to include additional parameters (languages, token, lang, sessionId) for API calls and telemetry logging.
src/store/{configureStore.js, slices/userJourney.slice.js} Introduced a new userJourney Redux slice with multiple action creators and integrated its reducer into the store configuration.
src/routes/index.js Modified TOKEN assignment logic by checking the login status (isLogin) in addition to retrieving the API token from local storage.

Sequence Diagram(s)

sequenceDiagram
    participant C as Component
    participant R as Redux Store
    participant S as Service
    C->>R: useSelector(userJourney)
    R-->>C: Returns { language, token, sessionId }
    C->>S: Call API/Telemetry with parameters
    S-->>C: Return response
Loading
sequenceDiagram
    participant U as User
    participant L as LoginPage
    participant R as Redux Store
    U->>L: Submit login credentials
    L->>R: Dispatch setToken & setProfileName actions
    R-->>L: Update userJourney state
    L->>localStorage: Set "isLogin" flag
Loading

Possibly related PRs

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

src/App.js

Oops! Something went wrong! :(

ESLint: 7.32.0

ESLint couldn't find the config "react-app" to extend from. Please check that the name of the config is correct.

The config "react-app" was referenced from the config file in "/package.json".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.

src/store/slices/userJourney.slice.js

Oops! Something went wrong! :(

ESLint: 7.32.0

ESLint couldn't find the config "react-app" to extend from. Please check that the name of the config is correct.

The config "react-app" was referenced from the config file in "/package.json".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 generate docstrings to generate docstrings for this 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 anywhere in the PR title to generate the title automatically.

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
Copy Markdown
Contributor

@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: 10

🔭 Outside diff range comments (2)
src/components/Layouts.jsx/MainLayout.jsx (1)

431-431: ⚠️ Potential issue

Add missing key prop in HeartBlack component

Similar to the previous issue, this mapped component is missing a key prop.

{[...Array(Math.max(0, blackLivesToShow) || 0).keys()]?.map(
  (elem, index) => (
-    <HeartBlack />
+    <HeartBlack key={index} />
  )
)}
🧰 Tools
🪛 Biome (1.9.4)

[error] 431-431: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)

src/components/AssesmentEnd/AssesmentEnd.jsx (1)

79-79: ⚠️ Potential issue

Missing dependencies in useEffect.

The useEffect has dependencies on Redux state (userJourney properties) that aren't included in the dependency array.

Add the necessary dependencies:

- }, [levelCompleteAudioSrc]);
+ }, [levelCompleteAudioSrc, dispatch, userJourney.language, userJourney.token, userJourney.sessionId, userJourney.previousLevel]);
🧹 Nitpick comments (18)
src/components/Practice/Mechanics3.jsx (1)

82-82: Add a fallback value for language.

While migrating from localStorage to Redux store is good, there's no default fallback value if userJourney or language is undefined.

-const lang = userJourney?.language;
+const lang = userJourney?.language || "en";
src/routes/index.js (1)

71-73: Consider completing the migration to Redux.

This file still uses localStorage for token information. For consistency with the PR objective of migrating to Redux, consider retrieving the token from the Redux store instead.

src/components/Practice/Mechanics6.jsx (2)

62-62: Add a fallback value for language.

Similar to Mechanics3.jsx, consider adding a default fallback value for language to prevent potential undefined behavior.

-const lang = userJourney?.language;
+const lang = userJourney?.language || "en";

101-103: Avoid redundant state extraction.

The function is re-extracting the language from userJourney when it could use the already defined lang variable from the component scope.

const getSimilarWords = async (wordForFindingHomophones) => {
-  const lang = userJourney?.language;
  // const isFillInTheBlanks = type === "fillInTheBlank";
  const wordToSimilar = wordForFindingHomophones
    ? wordForFindingHomophones
    : parentWords;
src/components/AssesmentEnd/AssesmentEnd.jsx (4)

45-48: Inconsistent fallback pattern for Redux values.

You're using a fallback to localStorage for previous_level but not for lang. This inconsistency could lead to bugs if the Redux store hasn't been properly initialized.

Consider using a consistent pattern for all values:

- const lang = userJourney.language;
+ const lang = userJourney.language || getLocalData("language");
const previous_level =
  userJourney?.previousLevel || getLocalData("previous_level");

48-48: Consider preserving the original level format.

You're removing the "m" prefix when dispatching to Redux, which creates inconsistency between the original format stored in localStorage and the format stored in Redux.

Consider storing the original format in Redux to maintain consistency:

- dispatch(setPreviousLevel(previous_level?.replace("m", "")));
+ dispatch(setPreviousLevel(previous_level));

Then handle the formatting when displaying or using the value.


54-56: Inconsistent level format between local state and Redux.

You're setting the local state with the full milestone level including the "m" prefix, but dispatching to Redux with the prefix removed. This creates inconsistency in how the level is stored.

Make the format consistent:

setLevel(data.milestone_level);
- dispatch(setUserLevel(data.milestone_level?.replace("m", "")));
+ dispatch(setUserLevel(data.milestone_level));

Or:

- setLevel(data.milestone_level);
+ setLevel(data.milestone_level?.replace("m", ""));
dispatch(setUserLevel(data.milestone_level?.replace("m", "")));

38-79: Consider cleanup of localStorage after migration.

As part of the migration to Redux, consider adding a cleanup strategy for localStorage values that are now stored in Redux to avoid confusion and stale data.

You could add a cleanup function that removes migrated values from localStorage once they're safely in Redux:

const cleanupLocalStorage = () => {
  // Only remove items that we're sure are in Redux
  if (userJourney.sessionId) localStorage.removeItem("sessionId");
  if (userJourney.language) localStorage.removeItem("language");
  if (userJourney.previousLevel) localStorage.removeItem("previous_level");
  // etc.
};

// Call this function at an appropriate time, e.g., after all values are fetched and dispatched
src/utils/constants.js (1)

3003-3003: Improve safety in accessing nested properties.

The change correctly shifts from localStorage to props for retrieving the milestone level. However, there's a potential issue with the optional chaining. If props.userJourney.getMilestone exists but data is undefined, accessing milestone_level could cause a runtime error.

- props?.userJourney?.getMilestone?.data.milestone_level || "m1";
+ props?.userJourney?.getMilestone?.data?.milestone_level || "m1";
src/utils/VoiceAnalyser.js (2)

281-282: Redundant language variable assignment.

The lang variable is redefined here when it's already defined at line 78. This creates unnecessary duplication.

You can remove this reassignment since the language is already available from earlier in the component:

-        const lang = userJourney.language || "ta";
-        fetchASROutput(lang, recordedAudioBase64);
+        fetchASROutput(userJourney.language || "ta", recordedAudioBase64);

346-348: Redundant language reassignment.

The language is retrieved again from Redux when it was already available from line 78.

Consider using the existing lang variable instead of creating a new one:

-      const lang = userJourney.language;
+      // Use the existing lang variable from line 78
src/components/Assesment/Assesment.jsx (5)

346-349: Potential data mismatch
Using a fallback from local storage might cause discrepancies if the Redux store is out-of-sync. Consider a uniform approach.


598-598: Fallback usage
Consider removing local storage fallback for session ID to avoid potential mismatches with Redux.


632-632: Local storage fallback
Could introduce duplicate states; consider a Redux-only approach.


657-657: Token fallback
Using local storage might cause inconsistencies; a single source of truth in Redux is often preferable.


700-700: Profile name fallback
Similarly, relying on local storage can lead to unsynchronized states.

src/views/Practice/Practice.jsx (1)

526-526: Use optional chaining for clarity.
Replace the logical AND check with optional chaining to improve readability.

- dispatch(setMechanismId((mechanism && mechanism.id) || ""));
+ dispatch(setMechanismId(mechanism?.id || ""));
🧰 Tools
🪛 Biome (1.9.4)

[error] 526-526: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

src/services/learnerAi/learnerAiService.js (1)

102-102: Simplify conditional expression and use optional chaining

The current implementation uses an unnecessary ternary operation with boolean literals and doesn't leverage optional chaining.

- is_mechanics: mechanism && mechanism?.id ? true : false,
+ is_mechanics: Boolean(mechanism?.id),
🧰 Tools
🪛 Biome (1.9.4)

[error] 102-102: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)


[error] 102-102: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 64abb16 and df915bd.

📒 Files selected for processing (21)
  • src/App.js (2 hunks)
  • src/components/Assesment/Assesment.jsx (7 hunks)
  • src/components/AssesmentEnd/AssesmentEnd.jsx (2 hunks)
  • src/components/DiscoverEnd/DiscoverEnd.jsx (3 hunks)
  • src/components/DiscoverSentance/DiscoverSentance.jsx (10 hunks)
  • src/components/Layouts.jsx/MainLayout.jsx (3 hunks)
  • src/components/Practice/Mechanics3.jsx (4 hunks)
  • src/components/Practice/Mechanics6.jsx (4 hunks)
  • src/routes/index.js (1 hunks)
  • src/services/callTelemetryIntract.js (1 hunks)
  • src/services/content/contentService.js (2 hunks)
  • src/services/learnerAi/learnerAiService.js (7 hunks)
  • src/services/orchestration/orchestrationService.js (7 hunks)
  • src/services/telementryService.js (4 hunks)
  • src/store/configureStore.js (1 hunks)
  • src/store/slices/userJourney.slice.js (1 hunks)
  • src/utils/VoiceAnalyser.js (8 hunks)
  • src/utils/constants.js (3 hunks)
  • src/views/AppContent/AppContent.jsx (1 hunks)
  • src/views/LoginPage/LoginPage.jsx (2 hunks)
  • src/views/Practice/Practice.jsx (19 hunks)
🧰 Additional context used
🧬 Code Definitions (3)
src/components/Practice/Mechanics3.jsx (9)
src/views/Practice/Practice.jsx (2) (2)
  • userJourney (49:49)
  • lang (77:77)
src/utils/VoiceAnalyser.js (2) (2)
  • userJourney (64:64)
  • lang (78:78)
src/components/Practice/Mechanics6.jsx (2) (2)
  • userJourney (53:53)
  • lang (62:62)
src/components/Layouts.jsx/MainLayout.jsx (1) (1)
  • userJourney (133:133)
src/App.js (1) (1)
  • userJourney (16:16)
src/components/DiscoverEnd/DiscoverEnd.jsx (1) (1)
  • userJourney (32:32)
src/components/AssesmentEnd/AssesmentEnd.jsx (1) (1)
  • userJourney (31:31)
src/components/Assesment/Assesment.jsx (3) (3)
  • userJourney (346:346)
  • userJourney (556:556)
  • lang (571:571)
src/components/DiscoverSentance/DiscoverSentance.jsx (1) (1)
  • userJourney (34:34)
src/utils/VoiceAnalyser.js (10)
src/views/Practice/Practice.jsx (2) (2)
  • userJourney (49:49)
  • lang (77:77)
src/components/Assesment/Assesment.jsx (3) (3)
  • userJourney (346:346)
  • userJourney (556:556)
  • lang (571:571)
src/components/Practice/Mechanics3.jsx (2) (2)
  • userJourney (63:63)
  • lang (82:82)
src/components/Layouts.jsx/MainLayout.jsx (1) (1)
  • userJourney (133:133)
src/components/Practice/Mechanics6.jsx (2) (2)
  • userJourney (53:53)
  • lang (62:62)
src/App.js (1) (1)
  • userJourney (16:16)
src/components/DiscoverSentance/DiscoverSentance.jsx (1) (1)
  • userJourney (34:34)
src/components/AssesmentEnd/AssesmentEnd.jsx (1) (1)
  • userJourney (31:31)
src/components/DiscoverEnd/DiscoverEnd.jsx (1) (1)
  • userJourney (32:32)
src/services/learnerAi/learnerAiService.js (2) (2)
  • updateLearnerProfile (113:125)
  • updateLearnerProfile (113:125)
src/components/Practice/Mechanics6.jsx (9)
src/components/Practice/Mechanics3.jsx (2) (2)
  • userJourney (63:63)
  • lang (82:82)
src/views/Practice/Practice.jsx (2) (2)
  • userJourney (49:49)
  • lang (77:77)
src/components/DiscoverSentance/DiscoverSentance.jsx (1) (1)
  • userJourney (34:34)
src/utils/VoiceAnalyser.js (2) (2)
  • userJourney (64:64)
  • lang (78:78)
src/components/Layouts.jsx/MainLayout.jsx (1) (1)
  • userJourney (133:133)
src/App.js (1) (1)
  • userJourney (16:16)
src/components/DiscoverEnd/DiscoverEnd.jsx (1) (1)
  • userJourney (32:32)
src/components/AssesmentEnd/AssesmentEnd.jsx (1) (1)
  • userJourney (31:31)
src/components/Assesment/Assesment.jsx (3) (3)
  • userJourney (346:346)
  • userJourney (556:556)
  • lang (571:571)
🪛 Biome (1.9.4)
src/components/Layouts.jsx/MainLayout.jsx

[error] 424-424: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)

src/views/Practice/Practice.jsx

[error] 526-526: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

src/services/learnerAi/learnerAiService.js

[error] 102-102: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)


[error] 102-102: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (110)
src/App.js (2)

16-16: LGTM! Good Redux integration.

Correctly implemented Redux selector to access the userJourney state.


51-51: Proper parameter passing via Redux state

Excellent use of the Redux state to pass parameters to the startEvent function instead of accessing localStorage directly.

src/services/callTelemetryIntract.js (1)

7-8: LGTM! Function signature updated properly.

The function now accepts parameters from Redux instead of accessing localStorage directly, which aligns with the PR objective.

src/components/Layouts.jsx/MainLayout.jsx (1)

133-133: LGTM! Good Redux integration.

Correctly implemented Redux selector to access the userJourney state.

src/components/Practice/Mechanics3.jsx (4)

22-22: Good addition of Redux import.

Adding the useSelector hook from react-redux is the correct approach for accessing the Redux store state.


61-61: Good formatting change.

Adding the trailing comma after setIsNextButtonCalled improves code consistency and makes future additions to the props list cleaner.


63-63: Correctly implemented Redux state access.

The userJourney selector is implemented properly, following the pattern used in other components like MainLayout, App.js, and other Practice components.


519-520: Good props passing update.

The trailing comma has been appropriately added to match the changes in the destructured props at the top of the component.

src/store/configureStore.js (3)

1-20: Good implementation of Redux store configuration.

The addition of the userJourney slice to the Redux store is implemented correctly. This provides a central place for managing user journey state that can be accessed throughout the application.


6-6: Good modular approach with separate slice file.

Importing the userJourneyReducer from a dedicated slice file follows good Redux organization practices by keeping related functionality together.


11-14: Properly added reducer to the store.

The userJourney reducer is correctly added to the combined reducers object, making it accessible via state.userJourney in components.

src/components/Practice/Mechanics6.jsx (2)

17-17: Good addition of Redux import.

Adding the useSelector hook from react-redux is the correct approach for accessing the Redux store state.


53-53: Correctly implemented Redux state access.

The userJourney selector is implemented properly, following the same pattern used across the application.

src/components/AssesmentEnd/AssesmentEnd.jsx (3)

66-74: fetchUserPoints call is dependent on Redux values.

You've updated the function to use Redux values, but there's no dependency in the useEffect for these values, which could lead to stale data if they change.

Make sure the fetchUserPoints call is updated if any of its dependencies change:

  useEffect(() => {
    // ...existing code...
  - }, [levelCompleteAudioSrc]);
  + }, [levelCompleteAudioSrc, userJourney.token, userJourney.language, userJourney.sessionId]);

Please verify that this won't cause infinite loops by ensuring that these values are stable between renders.


30-32: Good integration of Redux for state management.

You've correctly integrated Redux by adding the dispatch hook and selecting the userJourney state from the store.


57-61: Appropriate migration pattern with fallback.

You're correctly migrating to Redux while maintaining backward compatibility by falling back to localStorage when the value isn't in Redux yet.

src/views/LoginPage/LoginPage.jsx (4)

6-7: Redux imports properly included.

The new imports for Redux functionality are correctly added, bringing in the necessary hooks and actions for state management.


13-13: Dispatch hook initialized correctly.

The useDispatch hook is properly initialized to enable Redux action dispatching.


27-28: Local storage token management updated.

The code now stores login status in localStorage while properly removing the token storage, which aligns with the migration to Redux.


31-32: Redux state management implemented appropriately.

The token and profileName are now correctly stored in the Redux store using the appropriate action dispatches, which completes the migration from localStorage to Redux for these values.

src/utils/VoiceAnalyser.js (7)

38-38: Added Redux selector import correctly.

The Redux useSelector hook is properly imported for accessing the Redux store state.


64-64: Redux state accessed correctly via useSelector.

The component now properly uses the useSelector hook to access the userJourney state from Redux.


78-78: Language now retrieved from Redux state.

The code now appropriately uses the language setting from Redux state instead of local storage.


349-351: Consistent fallback pattern for sessionId and subSessionId.

The code properly implements fallbacks to local storage when Redux state is unavailable, ensuring backward compatibility during the migration.


369-370: Mechanism ID retrieval with fallback implemented correctly.

The code properly retrieves the mechanism ID from Redux with a fallback to local storage and an empty string default.


382-386: Token now passed to updateLearnerProfile from Redux.

The function call now correctly includes the token from Redux state, aligning with the updated function signature.


519-521: Telemetry service now uses Redux data.

The response function now receives language and token from Redux, completing the migration of these values from local storage.

src/components/DiscoverEnd/DiscoverEnd.jsx (7)

10-10: Updated imports for constants.

The import statement now properly includes only the necessary constants from the utils/constants file.


13-14: Redux imports added correctly.

The necessary Redux hooks and actions are properly imported for state management.


31-33: Redux hooks initialized correctly.

The component properly initializes the Redux hooks for dispatching actions and accessing state.


45-45: Language now retrieved from Redux state.

The code now correctly uses the language setting from the Redux state instead of local storage.


46-49: Token passed to API from Redux state.

The function call now correctly includes the token from Redux, ensuring proper authentication for the API request.


52-52: Redux action dispatched for user level.

The component now correctly dispatches an action to update the user level in Redux instead of storing it in local storage.


48-48:

Details

❓ Verification inconclusive

Missing null check for token.

The code directly uses userJourney.token without checking if it exists, which could cause issues if the token is undefined.

Consider adding a null check or fallback:

-        userJourney.token
+        userJourney?.token || getLocalData("apiToken")

Let's verify if this is a potential issue:


🏁 Script executed:

#!/bin/bash
# Check if there are other instances where token is used with a null check

# Find all uses of userJourney.token with optional chaining
echo "Checking for safe token access with optional chaining:"
rg "userJourney\?\.(token|token\?)" --type js --type jsx

# Find all direct uses of userJourney.token without optional chaining
echo "Checking for potentially unsafe token access:"
rg "userJourney\.token" --type js --type jsx | grep -v "userJourney\?\.(token|token\?)"

Length of output: 424


Token Null Check Required: Consider Using Optional Chaining and Fallback

It appears that in src/components/DiscoverEnd/DiscoverEnd.jsx (line 48) the code accesses userJourney.token directly without first checking if it exists. This could lead to runtime errors if token is undefined. We recommend updating this usage as follows:

-        userJourney.token
+        userJourney?.token || getLocalData("apiToken")

Our initial automated search for safe versus unsafe token accesses in JSX files encountered issues due to file type filtering. Please manually verify (or re-run an updated search script such as the one below) that similar token accesses elsewhere in the codebase are safeguarded:

#!/bin/bash
echo "Checking for safe token access with optional chaining in JSX files:"
rg "userJourney\?\.(token)" -g "*.jsx"
echo "Checking for unsafe token access in JSX files:"
rg "userJourney\.token" -g "*.jsx" | grep -v "userJourney\?\.(token)"
src/store/slices/userJourney.slice.js (6)

1-2: Redux toolkit imported correctly.

The createSlice function is properly imported from Redux toolkit for creating the slice.


3-18: User journey slice with comprehensive initial state.

The user journey slice is well-structured with a complete set of initial state properties to manage various aspects of the user journey.


19-56: Comprehensive set of reducers for state management.

The slice includes all necessary reducers to update each property in the state, maintaining a clean separation of concerns.


59-72: Actions exported correctly.

All action creators are properly exported for use throughout the application.


74-74: Reducer exported as default correctly.

The reducer is properly exported as the default export for inclusion in the Redux store.


16-16: ⚠️ Potential issue

Typo in state property name: subSessionIid.

There's a typo in the property name subSessionIid (should be subSessionId), which could cause inconsistencies when accessing this property throughout the application.

Fix the property name to match the expected convention:

-    subSessionIid: "",
+    subSessionId: "",

Likely an incorrect or invalid review comment.

src/components/Assesment/Assesment.jsx (16)

48-53: Successfully imported userJourney actions
No issues found.


556-557: Redux usage
Initialization of userJourney and dispatch looks correct.


563-563: Repeated dispatch risk
Ensure this is not called on every render to prevent unnecessary re-dispatch.


571-571: Default language
Fallback to "en" is acceptable for initialization.


577-577: Dispatching language
Keeping Redux state in sync is a solid approach.


579-579: Session ID management
Properly storing session ID in Redux.


589-589: Consistent naming
Setting profileName in Redux aligns well with prior usage.


591-593: Secure usage of token
Passing Redux token to getFetchMilestoneDetails ensures consistent authentication.


596-597: Check action signature
Verify if setGetMilestone(...getMilestoneDetails) matches the action’s expected payload shape.


602-602: Session ID dispatch
No issues identified here.


604-604: Fallback to "ta"
Ensure this default language is the intended secondary option.


609-609: Error handling
Consider adding retries or specialized error handling if token validation fails.


625-627: Consistent parameter usage
Passing language and token from Redux maintains centralized state control.


628-628: Action usage
Check if the action expects the entire object or a different shape.


636-636: Dispatch sessionId
Implementation looks correct.


644-644: fetchUserPoints call
Check for robust error handling, e.g. handling 401 or token expiry.

src/components/DiscoverSentance/DiscoverSentance.jsx (13)

29-30: Redux imports
Adopting Redux for subSessionId management is a good move.


33-34: Proper usage
Grabbing userJourney from the store aligns with recommended Redux patterns.


86-90: Error handling
Consider handling specific errors like 401 for token expiration.


103-104: Setting subSessionId
Creating a new unique ID for each question set is sensible.


129-129: Retrieve language
Using userJourney.language is clear for consistent UI.


153-157: Param usage
Providing token and language to fetchGetSetResult is consistent.


162-168: Add pointer
Ensure your logic handles repeat calls gracefully to avoid double increments.


182-182: Telemetry logs
Capturing token and language is helpful for debugging and analytics.


185-192: createLearnerProgress
All relevant parameters (session and token) are properly utilized.


210-214: Critical fetch parameters
Leveraging userJourney.token ensures authorized requests.


236-241: Word content retrieval
Consistent usage of Redux token is good.


278-283: fetchAssessmentData
Accepting token from Redux is an effective approach.


294-298: Pagination call
Continuing to pass token ensures consistent authentication across requests.

src/services/content/contentService.js (6)

7-8: Refined getHeaders
Allowing a token parameter provides flexibility for external control.


11-11: Bearer token usage
This follows a standard authentication scheme.


17-17: Signature update
Now fetchAssessmentData can accept a token for better authorization handling.


25-25: Headers injection
Good usage of getHeaders(token) for uniform request configuration.


33-38: Enhanced pagination function
Added token parameter keeps the calls Authorized consistently.


43-43: Forwarding token
Ensures subsequent content fetch requests remain secured.

src/views/Practice/Practice.jsx (19)

37-45: Redux setup looks good.
These imports correctly integrate Redux actions and selectors for centralized state management.


48-49: Dispatch and selector usage is appropriate.
The usage of useDispatch and useSelector aligns well with common Redux patterns.


77-77: Language retrieval from Redux is valid.
No issues with deriving lang from the userJourney slice.


124-124: Sub-session initialization seems appropriate.
Dispatching setSubSessionId(uniqueId()) is fine.


165-173: Correct usage for session data and practice progress.
Extracting lang, sessionId, and practiceProgress from Redux or local storage follows a sensible fallback pattern.


211-217: addPointer API call with Redux tokens.
All parameters, including the userJourney token and language, are passed appropriately.


223-242: Sub-session and logging updates are coherent.
Using userJourney data for sub-session IDs, tokens, and language is consistent with the Redux-based approach.


255-255: Setting previous level is straightforward.
No concerns; the dispatch call is correct.


265-288: addLesson calls with additional token parameter.
Incorporating userJourney.token is consistent with your new centralized approach.


306-307: Fetching new content with Redux token.
Utilizing userJourney.token ensures the correct credentials are included.


341-341: Synchronizing practice progress to Redux.
All dispatch calls for setPracticeProgress appear valid.

Also applies to: 513-513, 601-601


405-411: Session initialization and milestone retrieval.
Storing a newly generated sessionId in Redux and fetching milestone details with Redux credentials is correct.


422-425: getLessonProgressByID with Redux-based token and language.
No issues; parameters match the new signature.


433-433: Fetching user points with Redux-based credentials.
Implementation aligns well with the updated function signature.


453-455: Practice progress fallback logic.
Combining Redux and local storage data ensures backward compatibility.


530-530: Language fallback usage.
Defaulting to 'en' if userJourney.language is falsy is acceptable.


539-540: Session ID and language fallback.
These updated references to Redux ensure consistent state utilization.


560-560: Token parameter alignment.
Including userJourney.token in the object is correct and consistent.


579-579: Consistent token usage in API call.
Integration looks aligned with your Redux logic.

src/services/telementryService.js (4)

71-75: Extended signature for “start” function.
Adding languages and token to capture more context is a logical upgrade.


89-95: Updated “response” function with language and token.
Adapting getEventOptions arguments maintains consistency across the service.


100-105: New parameters in “Log” method.
Passing language and token to getEventOptions ensures standardized telemetry context.


227-283: Revised “getEventOptions” function.
Using languages || "ta" and token || null is fine, though confirm “ta” is indeed your intended default.

Would you like to confirm that “ta” is the correct fallback language?

src/services/orchestration/orchestrationService.js (7)

8-16: Flexible token headers.
Altering getHeaders to optionally accept a token aligns with your Redux-based approach.


18-29: getLessonProgressByID now includes token parameter.
No concerns; usage is consistent with the updated headers.


31-42: Enhanced “fetchUserPoints” signature.
Fetching points with explicit token, language, and session ID is well-organized.


44-61: “addPointer” with extended params.
Ensuring the request body and headers accept these arguments is an effective improvement.


66-69: Added token, language, and session ID in “createLearnerProgress.”
Implementation properly accounts for external token references.


84-84: getHeaders(token) usage.
Confirmed the request is generating the correct authorization header.


100-101: Augmented “addLesson” with token.
Updating the signature to utilize Redux-supplied tokens completes the refactor consistently.

Also applies to: 113-113

src/services/learnerAi/learnerAiService.js (5)

7-8: Good approach to maintain backward compatibility

The function now accepts a token parameter while maintaining backward compatibility by falling back to localStorage. This aligns with the PR objective of migrating from localStorage to Redux.


17-23: Implementation correctly supports Redux migration

The getContent function signature has been updated to accept a token parameter, which is then used when making the API call. This supports the PR goal of migrating from localStorage to Redux store.

Also applies to: 32-32


55-63: API integration successfully adapted for Redux

The function now accepts token, lang, and session_id parameters directly, properly integrating with the Redux state management approach. The implementation correctly uses these parameters in the API call.

Also applies to: 75-75


84-92: Function correctly adapted for Redux integration

The function now accepts token and lang parameters directly rather than retrieving them from localStorage. The language is also correctly included in the request body.

Also applies to: 101-101, 104-104


113-118: Successfully migrated to support token from Redux

The updateLearnerProfile function now accepts a token parameter and uses it when making the API call, aligning with the PR objective.

Comment thread src/views/AppContent/AppContent.jsx
Comment thread src/components/Layouts.jsx/MainLayout.jsx
Comment thread src/routes/index.js
Comment thread src/components/AssesmentEnd/AssesmentEnd.jsx
Comment thread src/utils/constants.js
Comment thread src/utils/constants.js
Comment thread src/utils/VoiceAnalyser.js Outdated
Comment thread src/store/slices/userJourney.slice.js
Comment thread src/components/DiscoverSentance/DiscoverSentance.jsx Outdated
Comment thread src/services/learnerAi/learnerAiService.js
Copy link
Copy Markdown
Contributor

@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: 0

🧹 Nitpick comments (7)
src/components/AssesmentEnd/AssesmentEnd.jsx (1)

46-53: Add fallback error handling around milestone fetch.
While the logic to retrieve language, previous level, and milestone details is solid, consider wrapping getFetchMilestoneDetails in a try/catch block or chain a .catch() for improved error handling if the request fails.

src/store/slices/userJourney.slice.js (1)

6-7: Consider the security implications of storing the token in Redux.
Storing tokens in a client-side store can pose security risks. If possible, evaluate using HTTP-only cookies instead.

src/components/DiscoverSentance/DiscoverSentance.jsx (1)

148-156: Fallback to local storage.
If the goal is full migration from local storage to Redux, consider removing the fallback to getLocalData("sub_session_id"). Otherwise, confirm the need for backward compatibility.

src/views/Practice/Practice.jsx (4)

168-173: Multiple fallbacks to local data.
You’re correctly combining Redux state with local storage fallback, but confirm if this is still needed or if you plan to remove local storage usage entirely.


222-223: Potentially remove local storage fallback.
Using userJourney?.subSessionId first is good. Reassess if the legacy fallback to getLocalData("sub_session_id") is still necessary.

Also applies to: 230-231


452-455: Check leftover local data usage.
Your fallback for practiceProgress is presumably for backward compatibility. Confirm if it can be safely removed.


526-526: Use optional chaining.
Consider simplifying dispatch(setMechanismId((mechanism && mechanism.id) || "")); to:

- dispatch(setMechanismId((mechanism && mechanism.id) || ""));
+ dispatch(setMechanismId(mechanism?.id || ""));
🧰 Tools
🪛 Biome (1.9.4)

[error] 526-526: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between df915bd and 844f74f.

📒 Files selected for processing (5)
  • src/components/AssesmentEnd/AssesmentEnd.jsx (2 hunks)
  • src/components/DiscoverSentance/DiscoverSentance.jsx (10 hunks)
  • src/store/slices/userJourney.slice.js (1 hunks)
  • src/utils/VoiceAnalyser.js (8 hunks)
  • src/views/Practice/Practice.jsx (19 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
src/views/Practice/Practice.jsx (2)
src/services/orchestration/orchestrationService.js (6) (6)
  • addPointer (44:61)
  • addPointer (44:61)
  • createLearnerProgress (63:91)
  • createLearnerProgress (63:91)
  • fetchUserPoints (31:42)
  • fetchUserPoints (31:42)
src/services/learnerAi/learnerAiService.js (4) (4)
  • getSetResultPractice (84:111)
  • getSetResultPractice (84:111)
  • getFetchMilestoneDetails (40:53)
  • getFetchMilestoneDetails (40:53)
🪛 Biome (1.9.4)
src/views/Practice/Practice.jsx

[error] 526-526: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (38)
src/components/AssesmentEnd/AssesmentEnd.jsx (5)

23-28: Imports for Redux slice look good.
No issues detected in your new imports from "react-redux" and the userJourney slice. This approach aligns well with your transition away from local storage.


31-31: Usage of useDispatch is appropriate.
No concerns regarding dispatch initialization. This is the standard pattern for triggering Redux actions.


32-32: Usage of useSelector for userJourney state is correct.
This correctly selects the required slice of state for further processing.


57-58: Ensure consistent session ID retrieval.
Retrieving sessionId from both userJourney and local storage can be deliberate. However, confirm whether you still need the local fallback or if all session IDs are fully managed by Redux now.


67-67: Kudos for including error handling in the promise chain.
Your .catch block for fetchUserPoints properly handles errors. No additional concerns here.

src/utils/VoiceAnalyser.js (7)

38-38: Importing useSelector is fine.
No issues found. This is consistent with the move to using Redux states.


64-64: Grabbing userJourney from Redux is correct.
The approach for retrieving the store slice is properly implemented.


78-78: Switch from local data to Redux language is accurate.
This ensures the language is always up to date and shared across components.


281-282: Verify the default fallback language.
You are defaulting to "ta" if userJourney.language is undefined. Please confirm that "ta" (Tamil) is indeed the intended fallback.


347-351: Reading session and subsession from Redux is consistent.
Fallback to local data is appropriate if your store initialization doesn't guarantee these states. No immediate concerns.


383-386: Update to pass userJourney token is valid.
Implementation is encompassed by the existing try/catch block, ensuring error handling if the request fails.


520-521: Telemetry call refactor is aligned with Redux usage.
Passing language and token from the store is consistent and promotes a single source of truth.

src/store/slices/userJourney.slice.js (1)

19-56: Overall slice design is well-structured.
You have clear, concise reducers and well-defined initial states. This pattern simplifies state management across the application.

src/components/DiscoverSentance/DiscoverSentance.jsx (8)

29-30: Good use of Redux imports.
Importing these Redux hooks and actions aligns with the PR objective of migrating from local storage to Redux.


33-34: Standard pattern for Redux state access.
Declaring dispatch and userJourney is correct and improves maintainability.


86-90: Consider guarding against missing Redux data.
If userJourney?.token, userJourney?.language, or userJourney?.sessionId is undefined, fetchUserPoints could fail silently. Verify that these Redux fields are always set or handle fallbacks.


103-105: Re-check effect dependencies.
Setting subSessionId in each re-render when questions changes might cause multiple resets. Confirm if this is intentional or if you only want one initialization.


129-129: Localized language reference looks good.
Switching from local storage to userJourney.language helps unify state management.


188-191: Consistent token usage.
Passing userJourney?.token and userJourney?.language into createLearnerProgress is an appropriate Redux-based approach.


210-213: Accurate pagination parameters.
Forwarding userJourney?.token helps maintain consistent authentication for content fetching.


237-240: Similar pagination call for words.
Excellent consistency in referencing Redux token and dynamic collectionId.

src/views/Practice/Practice.jsx (17)

37-45: Bulk Redux imports are correct.
These imports facilitate centralized state management for practice functionality.


48-49: Redux state access.
Using useDispatch and useSelector is a standard approach for functional components.


77-77: Language reference from Redux.
Directly destructuring language from userJourney is clean and consistent.


126-126: Validate repeated creation of subSessionId.
Check if setting a new subSessionId on every isShowCase toggle is desired, or if a single initialization would suffice.


165-165: Direct language usage.
Eliminating local storage for language here keeps the state consistent.


211-217: Smooth pointer addition.
Passing userJourney.token and userJourney.language along with sessionId ensures accurate orchestrations.


236-242: Enhanced telemetry logging with Redux data.
Passing userJourney?.language and userJourney?.token standardizes the log context.


245-253: Progress creation alignment.
Updating createLearnerProgress with Redux-provided arguments ensures consistent, centralized session data.


255-255: Previous level tracking in Redux.
Good addition of setPreviousLevelData to store the new level details reliably.


288-288: Token parameter for lesson addition.
Great job referencing userJourney.token for consistent authentication.


305-307: Consistent call to getContent.
Using userJourney.token avoids reliance on local storage.


342-342: Practice progress in Redux.
Storing updated practice progress in Redux fosters a unified state approach.


408-411: Fetching milestone details with Redux credentials.
Using userJourney.language and userJourney.token is consistent with the new approach.


414-414: Milestone state storage.
Dispatching setGetMilestone keeps all milestone data in one place.


422-425: Querying lesson progress by ID.
Correctly referencing Redux’s language and token.


433-437: User points from Redux session.
Fetching points with userJourney.token and userJourney.language is consistent.


512-512: Unified practice progress approach.
Dispatching setPracticeProgress complements the code modifications for the Redux flow.

Copy link
Copy Markdown
Contributor

@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: 2

🧹 Nitpick comments (4)
src/views/Practice/Practice.jsx (4)

166-174: Consider refactoring fallback pattern for better readability.

The code correctly prioritizes Redux state over local storage, but the nested fallback pattern could be simplified for better readability.

-const lang = userJourney.language;
-const sessionId = userJourney?.sessionId || getLocalData("sessionId");
-let practiceProgress =
-  userJourney?.practiceProgress ||
-  JSON.parse(getLocalData("practiceProgress")) ||
-  {};
+const lang = userJourney.language;
+const sessionId = userJourney?.sessionId || getLocalData("sessionId");
+const localPracticeProgress = getLocalData("practiceProgress");
+let practiceProgress = userJourney?.practiceProgress || 
+  (localPracticeProgress ? JSON.parse(localPracticeProgress) : {});

223-233: Ensure consistent access pattern for subSessionId.

The code uses a different pattern to access the subSessionId compared to other Redux state values. Consider using the same pattern for consistency.

-const sub_session_id =
-  userJourney?.subSessionId || getLocalData("sub_session_id");
+const sub_session_id = userJourney?.subSessionId || getLocalData("sub_session_id");

The API call correctly uses Redux state data for token and language parameters.


443-446: Same fallback pattern reused.

The same fallback pattern is used here as earlier in the code. Consider applying the same refactoring suggestion to simplify the logic.

-let practiceProgress =
-  userJourney?.practiceProgress ||
-  JSON.parse(getLocalData("practiceProgress")) ||
-  {};
+const localPracticeProgress = getLocalData("practiceProgress");
+let practiceProgress = userJourney?.practiceProgress || 
+  (localPracticeProgress ? JSON.parse(localPracticeProgress) : {});

517-517: Fix mechanism ID update logic with optional chaining.

There's an opportunity to use optional chaining for better code readability, which was also highlighted by static analysis.

-dispatch(setMechanismId((mechanism && mechanism.id) || ""));
+dispatch(setMechanismId(mechanism?.id || ""));
🧰 Tools
🪛 Biome (1.9.4)

[error] 517-517: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 844f74f and 8a817f5.

📒 Files selected for processing (6)
  • src/components/Assesment/Assesment.jsx (6 hunks)
  • src/components/AssesmentEnd/AssesmentEnd.jsx (2 hunks)
  • src/components/DiscoverEnd/DiscoverEnd.jsx (2 hunks)
  • src/components/DiscoverSentance/DiscoverSentance.jsx (11 hunks)
  • src/utils/VoiceAnalyser.js (8 hunks)
  • src/views/Practice/Practice.jsx (19 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/utils/VoiceAnalyser.js
🧰 Additional context used
🧬 Code Definitions (5)
src/components/DiscoverEnd/DiscoverEnd.jsx (12)
src/components/DiscoverSentance/DiscoverSentance.jsx (3) (3)
  • dispatch (33-33)
  • userJourney (34-34)
  • token (55-55)
src/views/Practice/Practice.jsx (5) (5)
  • dispatch (48-48)
  • userJourney (49-49)
  • level (64-64)
  • token (82-82)
  • lang (77-77)
src/components/Assesment/Assesment.jsx (6) (6)
  • dispatch (557-557)
  • userJourney (346-346)
  • userJourney (556-556)
  • level (569-569)
  • virtualId (655-655)
  • lang (571-571)
src/components/AssesmentEnd/AssesmentEnd.jsx (4) (4)
  • dispatch (31-31)
  • userJourney (32-32)
  • shake (33-33)
  • level (34-34)
src/views/LoginPage/LoginPage.jsx (1) (1)
  • dispatch (13-13)
src/App.js (1) (1)
  • userJourney (16-16)
src/components/Practice/Mechanics3.jsx (3) (3)
  • userJourney (63-63)
  • shake (69-69)
  • lang (82-82)
src/components/Practice/Mechanics6.jsx (3) (3)
  • userJourney (53-53)
  • shake (59-59)
  • lang (62-62)
src/hooks/usePreloadAudio.jsx (1) (1)
  • usePreloadAudio (3-28)
src/views/AppContent/AppContent.jsx (1) (1)
  • virtualId (7-7)
src/utils/constants.js (2) (2)
  • getLocalData (5-9)
  • getLocalData (5-9)
src/services/learnerAi/learnerAiService.js (2) (2)
  • getFetchMilestoneDetails (40-53)
  • getFetchMilestoneDetails (40-53)
src/components/AssesmentEnd/AssesmentEnd.jsx (2)
src/services/learnerAi/learnerAiService.js (2) (2)
  • getFetchMilestoneDetails (40-53)
  • getFetchMilestoneDetails (40-53)
src/services/orchestration/orchestrationService.js (2) (2)
  • fetchUserPoints (31-42)
  • fetchUserPoints (31-42)
src/components/DiscoverSentance/DiscoverSentance.jsx (2)
src/services/orchestration/orchestrationService.js (6) (6)
  • fetchUserPoints (31-42)
  • fetchUserPoints (31-42)
  • addPointer (44-61)
  • addPointer (44-61)
  • createLearnerProgress (63-91)
  • createLearnerProgress (63-91)
src/services/content/contentService.js (2) (2)
  • fetchAssessmentData (17-32)
  • fetchAssessmentData (17-32)
src/components/Assesment/Assesment.jsx (3)
src/services/userservice/userService.js (2) (2)
  • fetchVirtualId (7-17)
  • fetchVirtualId (7-17)
src/services/learnerAi/learnerAiService.js (2) (2)
  • getFetchMilestoneDetails (40-53)
  • getFetchMilestoneDetails (40-53)
src/services/orchestration/orchestrationService.js (2) (2)
  • fetchUserPoints (31-42)
  • fetchUserPoints (31-42)
src/views/Practice/Practice.jsx (3)
src/services/telementryService.js (3) (3)
  • token (19-19)
  • Log (100-120)
  • Log (100-120)
src/services/orchestration/orchestrationService.js (6) (6)
  • addPointer (44-61)
  • addPointer (44-61)
  • createLearnerProgress (63-91)
  • createLearnerProgress (63-91)
  • fetchUserPoints (31-42)
  • fetchUserPoints (31-42)
src/services/learnerAi/learnerAiService.js (4) (4)
  • getSetResultPractice (84-111)
  • getSetResultPractice (84-111)
  • getFetchMilestoneDetails (40-53)
  • getFetchMilestoneDetails (40-53)
🪛 Biome (1.9.4)
src/views/Practice/Practice.jsx

[error] 517-517: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (53)
src/components/DiscoverEnd/DiscoverEnd.jsx (5)

10-14: Good update of imports for Redux integration

The imports have been correctly updated to support the migration from localStorage to Redux store management. Adding the Redux hooks (useDispatch, useSelector) and the Redux action (setUserLevel) is appropriate for the changes being made.


31-33: Proper initialization of Redux hooks

The Redux hooks are correctly set up at the component level, making the state accessible throughout the component.


40-41: Good fallback mechanism for token retrieval

Using Redux with localStorage fallback ensures a smooth transition from the old approach to the new state management system.


45-47: Successfully migrated language state to Redux

The language is now properly retrieved from the Redux store instead of localStorage, which aligns with the PR objectives.


50-50: Properly dispatching user level to Redux store

The setUserLevel action is correctly dispatched to update the Redux store with the milestone level data.

src/components/AssesmentEnd/AssesmentEnd.jsx (7)

23-28: Good Redux action imports

The necessary Redux actions are properly imported for state management. This includes setPreviousLevelData, setSessionId, and setUserLevel, which are all needed for the component's functionality.


31-32: Proper initialization of Redux hooks

The Redux hooks are correctly set up at the component level, making the state accessible throughout the component.


41-41: Good fallback mechanism for token retrieval

Similar to DiscoverEnd.jsx, using Redux with localStorage fallback ensures a smooth transition from the old approach to the new state management system.


47-51: Complete migration of previousLevel state to Redux

The previous level is now correctly retrieved from Redux with a fallback to local storage, and the appropriate action is dispatched to update the state.


55-56: Successfully migrated user level and session ID to Redux

The user level is properly dispatched to the Redux store, and the session ID is retrieved with a fallback mechanism, ensuring data consistency.


59-59: Proper Redux update for new session ID

When a new session ID is generated, it's correctly dispatched to the Redux store.


65-65: Updated API call with Redux state parameters

The fetchUserPoints function is now correctly called with parameters from the Redux store, ensuring consistent state management.

src/components/Assesment/Assesment.jsx (12)

48-53: Comprehensive import of Redux actions

All necessary Redux actions are properly imported for state management, including setGetMilestone, setLanguage, setProfileName, and setSessionId.


556-557: Proper initialization of Redux hooks

The Redux hooks are correctly set up at the component level, making the state accessible throughout the component.


563-563: Correct dispatch for setting profile name

The profile name is properly dispatched to the Redux store when available from the JWT token.


571-571: Language state now from Redux

The initial state for language is correctly set using the Redux store with a fallback to a default value.


573-573: Token retrieval from Redux

The token is properly retrieved from Redux with a fallback to localStorage, maintaining backward compatibility.


578-580: Migrated language and session ID updates to Redux

The component now correctly dispatches the language and session ID to the Redux store instead of setting them in localStorage.


602-602: Proper language dispatch

The language is correctly dispatched to the Redux store with a fallback to a default value.


607-614: Updated API call with error handling

The fetchUserPoints function is now called with parameters from the Redux store, and proper error handling is implemented.


622-627: Updated milestone retrieval with Redux parameters

The getFetchMilestoneDetails function now receives parameters from the Redux store, and the response is correctly dispatched to update the Redux state.


630-634: Session ID handling with Redux

The session ID is properly retrieved from Redux with a fallback to local storage, and a new session ID is dispatched to the Redux store when needed.


642-649: Updated points retrieval with error handling

The user points are now fetched using Redux state parameters, with proper error handling in place.


697-697: Profile name retrieval with Redux fallback

The component now correctly retrieves the profile name from Redux with a fallback to local storage.

src/components/DiscoverSentance/DiscoverSentance.jsx (14)

29-30: Good Redux imports

The necessary Redux hooks and action are properly imported for state management.


33-34: Proper initialization of Redux hooks

The Redux hooks are correctly set up at the component level, making the state accessible throughout the component.


55-55: Token retrieval from Redux

The token is properly retrieved from Redux with a fallback to localStorage, maintaining backward compatibility.


87-87: Updated points retrieval with Redux parameters

The fetchUserPoints function now correctly receives parameters from the Redux store.


100-100: Sub-session ID now managed in Redux

The sub-session ID is now correctly dispatched to the Redux store using setSubSessionId.


126-126: Language retrieval from Redux

The language is now properly retrieved from the Redux store instead of local storage.


144-154: Proper parameter passing to fetchGetSetResult

The function call now includes parameters from the Redux store, ensuring consistent state management across API calls.


159-165: Updated addPointer call with Redux parameters

The addPointer function now receives parameters from the Redux store, maintaining consistency in the API calls.


179-179: Updated logging with Redux parameters

The Log function now receives parameters from the Redux store.


206-211: Updated fetchPaginatedContent call

The function call now correctly includes the token parameter from Redux.


233-238: Updated fetchPaginatedContent call for words

The function call now correctly includes the token parameter from Redux.


275-275: Language retrieval from Redux

The language is now properly retrieved from the Redux store.


277-277: Updated fetchAssessmentData call

The fetchAssessmentData function now receives parameters from the Redux store.


287-292: Updated fetchPaginatedContent call

The function call now correctly includes the token parameter from Redux.

src/views/Practice/Practice.jsx (15)

37-45: Redux integration correctly implemented.

The Redux hooks and action creators are properly imported to support the transition from local storage to Redux-based state management. The imports include all necessary actions for updating the user journey in the Redux store.


48-49: Redux hooks effectively set up.

The useDispatch and useSelector hooks are correctly implemented to access and update the Redux store. The userJourney state is properly extracted from the Redux store.


77-77: User data now sourced from Redux state.

The migration from local storage to Redux state for user data like language and token is implemented correctly. The token implementation includes a fallback to local storage, which is a good practice during migration to ensure backward compatibility.

Also applies to: 82-82


127-127: Redux action dispatched correctly for unique ID.

The setSubSessionId action is properly dispatched with a unique ID when the showcase state changes.


212-218: API parameters updated to use Redux state.

The addPointer function now correctly receives parameters from the Redux store, ensuring consistent user session data is sent to the API.


237-237: Telemetry logging updated with Redux data.

The Log function now correctly uses data from the Redux store for language and token parameters.


241-248: API parameters successfully migrated to Redux state.

The createLearnerProgress function now correctly receives parameters from the Redux store, including the token and language.


250-250: Previous level data now updated via Redux.

The previous level data is now correctly stored in the Redux store using dispatch(setPreviousLevelData()).


336-336: Practice progress updates now managed through Redux.

Updating practice progress is now correctly done through Redux actions instead of directly modifying local storage.

Also applies to: 354-354


401-410: Session management and milestones now use Redux.

The code correctly stores session ID and milestone data in Redux instead of just in local storage. The changes properly maintain app functionality while transitioning to centralized state management.


417-420: API calls updated with Redux state parameters.

The getLessonProgressByID and fetchUserPoints function calls now correctly use data from the Redux store for language and token parameters.

Also applies to: 428-428


503-503: Redux state update correctly implemented.

The practice progress is correctly updated in the Redux store after API operations.


520-522: Fallback provided for language in getCurrentContent.

The code correctly uses the Redux state for language with a fallback to "en", maintaining functionality during the transition.


530-531: Consistent Redux state usage throughout the component.

User journey data is consistently accessed from Redux throughout the component, with fallbacks to local storage where needed.


591-591: Redux actions dispatched at appropriate locations.

The practice progress is consistently updated in the Redux store at all necessary points in the component lifecycle.

Comment thread src/components/Assesment/Assesment.jsx Outdated
Comment thread src/components/DiscoverSentance/DiscoverSentance.jsx
Copy link
Copy Markdown
Contributor

@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: 0

🧹 Nitpick comments (1)
src/components/DiscoverSentance/DiscoverSentance.jsx (1)

272-307: Consider adding dependencies to useEffect.

The useEffect hook has no dependencies array, but it uses Redux state values. If these values change, the effect won't re-run.

-  useEffect(() => {
+  useEffect(() => {
     (async () => {
       let quesArr = [];
       try {
         const lang = userJourney?.language;
         // Fetch assessment data
         const resAssessment = await fetchAssessmentData(lang, token);
         const sentences = resAssessment?.data?.find(
           (elem) => elem.category === "Sentence"
         );

         if (!sentences?.collectionId) {
           console.error("No collection ID found for sentences.");
           return;
         }
         // Fetch paginated content
         const resPagination = await fetchPaginatedContent(
           sentences.collectionId,
           1,
           5,
           token
         );

         // Update state
         setCurrentContentType("Sentence");
         setTotalSyllableCount(resPagination?.totalSyllableCount);
         setCurrentCollectionId(sentences?.collectionId);
         setAssessmentResponse(resAssessment);
         setLocalData("storyTitle", sentences?.name);
         quesArr = [...quesArr, ...(resPagination?.data || [])];
         setQuestions(quesArr);
       } catch (error) {
         console.error("Error fetching data:", error);
       }
     })();
-  }, []);
+  }, [userJourney?.language, token]);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8a817f5 and be7d98d.

📒 Files selected for processing (2)
  • src/components/Assesment/Assesment.jsx (6 hunks)
  • src/components/DiscoverSentance/DiscoverSentance.jsx (11 hunks)
🧰 Additional context used
🧬 Code Definitions (2)
src/components/Assesment/Assesment.jsx (2)
src/services/learnerAi/learnerAiService.js (2) (2)
  • getFetchMilestoneDetails (40-53)
  • getFetchMilestoneDetails (40-53)
src/services/orchestration/orchestrationService.js (2) (2)
  • fetchUserPoints (31-42)
  • fetchUserPoints (31-42)
src/components/DiscoverSentance/DiscoverSentance.jsx (11)
src/views/Practice/Practice.jsx (5) (5)
  • dispatch (48-48)
  • userJourney (49-49)
  • token (82-82)
  • lang (77-77)
  • totalSyllableCount (78-78)
src/components/Assesment/Assesment.jsx (4) (4)
  • dispatch (557-557)
  • userJourney (346-346)
  • userJourney (556-556)
  • lang (571-571)
src/components/AssesmentEnd/AssesmentEnd.jsx (2) (2)
  • dispatch (31-31)
  • userJourney (32-32)
src/views/LoginPage/LoginPage.jsx (1) (1)
  • dispatch (13-13)
src/utils/VoiceAnalyser.js (2) (2)
  • userJourney (64-64)
  • lang (78-78)
src/App.js (1) (1)
  • userJourney (16-16)
src/components/Layouts.jsx/MainLayout.jsx (1) (1)
  • userJourney (133-133)
src/components/Practice/Mechanics6.jsx (2) (2)
  • userJourney (53-53)
  • lang (62-62)
src/components/Practice/Mechanics3.jsx (2) (2)
  • userJourney (63-63)
  • lang (82-82)
src/services/orchestration/orchestrationService.js (6) (6)
  • fetchUserPoints (31-42)
  • fetchUserPoints (31-42)
  • addPointer (44-61)
  • addPointer (44-61)
  • createLearnerProgress (63-91)
  • createLearnerProgress (63-91)
src/services/content/contentService.js (2) (2)
  • fetchAssessmentData (17-32)
  • fetchAssessmentData (17-32)
🔇 Additional comments (25)
src/components/Assesment/Assesment.jsx (13)

48-53: New Redux imports for user journey management.

Good addition of imports for Redux actions to manage user journey state via Redux instead of localStorage.


346-349: Good migration to Redux with fallback pattern.

The ProfileHeader component now properly retrieves language and profileName from Redux state, with a fallback to localStorage. This creates a smooth transition path while ensuring the application remains functional.


556-557: Appropriate Redux hook setup in Assesment component.

The useSelector and useDispatch hooks are correctly set up to connect the component to the Redux store.


563-564: Profile name dispatch on JWT token decode.

The username is now correctly dispatched to Redux when decoded from the JWT token.


571-574: Consistent state management approach for language and token.

The component now uses Redux state first with a fallback to localStorage, which is a good pattern for transitioning from localStorage to Redux.


578-580: Proper dispatch to Redux store after data retrieval.

Language and session ID are now correctly dispatched to the Redux store.


590-595: Redux state updates and API service integration.

The component now correctly dispatches user data to Redux and integrates with API services by passing the token from Redux state.


596-603: Good state management with fallback pattern.

The code properly retrieves the session ID from Redux with a fallback to localStorage, and then dispatches both session ID and language to Redux.


607-614: Improved error handling for fetchUserPoints.

The fetchUserPoints function now uses Redux state for parameters and includes proper error handling.


622-627: Proper API integration with Redux state.

The getFetchMilestoneDetails call now correctly uses Redux state and dispatches the results to Redux.


630-635: Consistent session ID management.

Session ID management follows the same pattern with Redux state as the primary source and localStorage as a fallback.


642-650: Proper error handling for fetchUserPoints with Redux state.

The second fetchUserPoints call also uses Redux state for parameters and includes proper error handling.


697-698: Consistent retrieval pattern in redirect function.

The handleRedirect function uses the same pattern of retrieving data from Redux first with a fallback to localStorage.

src/components/DiscoverSentance/DiscoverSentance.jsx (12)

29-30: Good addition of Redux imports.

Adding Redux hooks and actions for state management is a good architectural decision.


33-34: Proper Redux hook setup in SpeakSentenceComponent.

The useDispatch and useSelector hooks are correctly set up to connect the component to the Redux store.


55-55: Consistent token retrieval pattern.

The token is retrieved from Redux first with a fallback to localStorage.


85-96: Improved fetchUserPoints with Redux state.

The fetchUserPoints function now uses Redux state for parameters, which is consistent with the migration to Redux.


98-102: Migration from localStorage to Redux for subSessionId.

The component now dispatches subSessionId to Redux instead of using setLocalData, which is consistent with the migration goal.


126-126: Cleaner language retrieval from Redux.

Using Redux for language state simplifies the code and improves maintainability.


144-154: Proper API integration with Redux state.

The fetchGetSetResult function now receives parameters from Redux state, which is consistent with the migration to Redux.


159-170: Consistent addPointer integration with Redux.

The addPointer function now also uses parameters from Redux state.


179-179: Redux integration for telemetry logging.

The Log function now uses language from Redux state.


182-193: Complete migration to Redux for learner progress.

The createLearnerProgress function now correctly receives all required parameters from Redux state.


208-212: Consistent API integration with token from Redux.

All fetchPaginatedContent calls now use the token from Redux state.

Also applies to: 235-239, 289-293


276-278: Consistent API integration for assessment data.

The fetchAssessmentData function now receives language and token from Redux state.

Copy link
Copy Markdown
Contributor

@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: 3

🔭 Outside diff range comments (1)
src/components/AssesmentEnd/AssesmentEnd.jsx (1)

78-78: ⚠️ Potential issue

Missing dependencies in useEffect dependency array.

The effect function depends on multiple values like userJourney, token, and potentially others, but the dependency array only includes levelCompleteAudioSrc. This could lead to stale data being used if these dependencies change.

- }, [levelCompleteAudioSrc]);
+ }, [levelCompleteAudioSrc, userJourney, token, dispatch]);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between be7d98d and 9346de0.

📒 Files selected for processing (2)
  • src/App.js (2 hunks)
  • src/components/AssesmentEnd/AssesmentEnd.jsx (2 hunks)
🧰 Additional context used
🧬 Code Definitions (2)
src/components/AssesmentEnd/AssesmentEnd.jsx (2)
src/services/learnerAi/learnerAiService.js (2) (2)
  • getFetchMilestoneDetails (40-53)
  • getFetchMilestoneDetails (40-53)
src/services/orchestration/orchestrationService.js (2) (2)
  • fetchUserPoints (31-42)
  • fetchUserPoints (31-42)
src/App.js (3)
src/services/telementryService.js (1) (1)
  • TOKEN (218-218)
src/services/userservice/userService.js (1) (1)
  • TOKEN (20-20)
src/services/callTelemetryIntract.js (2) (2)
  • startEvent (7-9)
  • startEvent (7-9)
🔇 Additional comments (3)
src/App.js (1)

16-18: Correctly implemented Redux state access with localStorage fallback.

The use of useSelector to access the Redux store and the fallback to localStorage for the token is a good practice for gradual migration from local storage to Redux state management.

src/components/AssesmentEnd/AssesmentEnd.jsx (2)

23-28: Imports correctly set up for Redux integration.

The necessary imports for Redux hooks and actions are properly added.


38-38: Correctly implemented token retrieval from Redux with localStorage fallback.

The implementation follows the same pattern used in App.js, maintaining consistency throughout the application.

Comment thread src/App.js
Comment thread src/components/AssesmentEnd/AssesmentEnd.jsx
Comment thread src/components/AssesmentEnd/AssesmentEnd.jsx
@sonarqubecloud
Copy link
Copy Markdown

Copy link
Copy Markdown
Contributor

@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: 0

🧹 Nitpick comments (2)
src/store/slices/userJourney.slice.js (2)

1-16: The initial state is well-structured but has some inconsistencies.

The Redux slice's initial state covers all necessary user journey properties. However, there are two areas for improvement:

  1. The property getMilestone (line 8) suggests a function rather than data. Consider renaming to milestone or milestoneData for clarity.

  2. Inconsistent naming conventions: most properties use camelCase, but mechanism_id uses snake_case (line 10). Consider standardizing to camelCase for all properties (e.g., mechanismId).


55-57: Action and state property names are inconsistent.

The action is named setPreviousLevelData but it updates state.previousLevel. Consider renaming either the action to setPreviousLevel or the state property to previousLevelData for consistency.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9346de0 and 4e91d83.

📒 Files selected for processing (2)
  • src/App.js (4 hunks)
  • src/store/slices/userJourney.slice.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/App.js
🔇 Additional comments (2)
src/store/slices/userJourney.slice.js (2)

18-62: Reducers are implemented correctly and follow best practices.

The slice implementation follows Redux Toolkit's best practices with simple, focused reducers that each handle a single concern. The resetState reducer provides a clean way to reset the entire state when needed.


64-80: Properly exported all actions and reducer.

All action creators are correctly exported individually, and the reducer is exported as default, following Redux best practices.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant