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

fix: set localStorage for endpoints on login page #86

Merged
merged 2 commits into from
Jan 17, 2025

Conversation

aum-deriv
Copy link
Collaborator

@aum-deriv aum-deriv commented Jan 17, 2025

πŸ”— Linked Issue

❓ Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no API changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

πŸ“ Description

πŸ§ͺ How Has This Been Tested?

πŸ“· Screenshots (if appropriate)

Summary by Sourcery

Bug Fixes:

  • Set default endpoint settings in localStorage on the login page if they are not already set.

Copy link

sourcery-ai bot commented Jan 17, 2025

Reviewer's Guide by Sourcery

This PR fixes a bug where localStorage was not being set for endpoints on the login page. The change introduces a useEffect hook that checks for stored endpoint settings upon app initialization. If no settings are found, default values are stored in localStorage.

Sequence diagram for endpoint settings initialization

sequenceDiagram
    participant App
    participant LocalStorage
    participant Config

    App->>Config: getStoredEndpointSettings()
    Config->>LocalStorage: Check settings
    LocalStorage-->>Config: Return stored settings
    Config-->>App: Return settings

    alt No stored settings
        App->>Config: getDefaultServer()
        Config-->>App: Return default server
        App->>Config: getDefaultAppId()
        Config-->>App: Return default app ID
        App->>Config: setEndpointSettings(server, appId)
        Config->>LocalStorage: Store settings
    end
Loading

Flow diagram for endpoint settings initialization

graph TD
    A[Start] --> B{Check stored
endpoint settings}
    B -->|Settings exist| C[Continue with
existing settings]
    B -->|No settings| D[Get default server]
    D --> E[Get default app ID]
    E --> F[Set endpoint settings
in localStorage]
    F --> C
Loading

File-Level Changes

Change Details Files
Set default endpoints in localStorage if none exist
  • Added a useEffect hook to check for existing endpoint settings in localStorage on component mount.
  • Set default endpoint settings using setEndpointSettings if no stored settings are found.
  • Used getStoredEndpointSettings, getDefaultServer, and getDefaultAppId from config file to manage endpoint settings and defaults.
  • Import necessary functions from config file
src/App.jsx

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time. You can also use
    this command to specify where the summary should be inserted.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Collaborator

@review-deriv review-deriv left a comment

Choose a reason for hiding this comment

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

AI Code Review

⚠️ IMPORTANT: This review is AI-generated and should be validated by human reviewers
πŸ”΄ BUGS & LOGICAL ISSUES:
β€’ Incomplete validation of stored settings:
Description: The code checks if getStoredEndpointSettings() returns a falsy value and then sets endpoint defaults. However, there is no validation to ensure β€œstoredSettings” is actually correct or complete. If it is partially corrupt or missing certain fields (not strictly falsy), the application might continue with invalid settings.
Potential impacts: Users could end up running the app with incorrect or partially set configurations without noticing.
Reproduction scenarios:
1. If getStoredEndpointSettings() returns an empty object instead of null/undefined, the current logic will not reset the settings.
2. If getStoredEndpointSettings() throws or returns malformed data, the effect might fail silently.
Fix implementation:
useEffect(() => {
let storedSettings;
try {
storedSettings = getStoredEndpointSettings();
// Add a check for structure or required fields:
if (!storedSettings || !storedSettings.server || !storedSettings.appId) {
throw new Error("Invalid or incomplete stored settings");
}
} catch (error) {
// Fallback to defaults if settings are invalid or retrieval fails
setEndpointSettings(getDefaultServer(), getDefaultAppId());
}
}, []);

🟑 RELIABILITY CONCERNS:
β€’ Potential lack of error handling if config retrieval fails:
Edge cases: For instance, if the stored settings are fetched from local storage and local storage is disabled or corrupted, getStoredEndpointSettings() might throw an error or return invalid data.
Potential failure scenarios: The browser might be in private mode or under strict security policies and fail to read from local storage, causing an unhandled exception.
Mitigation steps:
- Wrap getStoredEndpointSettings() in a try/catch block.
- Provide a user-facing warning or fallback UI if reading from storage fails.
- Implement robust checks for presence and validity of stored settings.

πŸ’‘ ROBUSTNESS IMPROVEMENTS:
β€’ Error handling enhancements:

  • Return or log detailed error messages when getStoredEndpointSettings() or setEndpointSettings() fails:
    try {
    const storedSettings = getStoredEndpointSettings();
    if (!storedSettings) {
    setEndpointSettings(getDefaultServer(), getDefaultAppId());
    }
    } catch (error) {
    console.error("Failed to retrieve settings:", error);
    setEndpointSettings(getDefaultServer(), getDefaultAppId());
    }

β€’ Input validation additions:

  • Validate the shape of storedSettings and handle unexpected fields to avoid future incompatibilities:
    const validateSettings = (settings) => {
    return settings && typeof settings.server === "string" && typeof settings.appId === "number";
    };

β€’ State management improvements:

  • Consider whether the effect should run again if storedSettings changes externally. If so, remove [] dependency to re-validate when needed:
    useEffect(() => {
    // logic...
    }, [/* dependencies as needed */]);

β€’ Code example for improved checks and fallback:
useEffect(() => {
try {
const storedSettings = getStoredEndpointSettings();
if (!validateSettings(storedSettings)) {
console.warn("Stored settings are incomplete or invalid, using defaults.");
setEndpointSettings(getDefaultServer(), getDefaultAppId());
}
} catch (err) {
console.error("Error retrieving stored settings:", err);
setEndpointSettings(getDefaultServer(), getDefaultAppId());
}
}, []);

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @aum-deriv - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Please fill out the PR description template, especially the sections describing the issue being fixed and how the changes were tested. This context is important for changes affecting application initialization.
Here's what I looked at during the review
  • 🟑 General issues: 1 issue found
  • 🟒 Security: all looks good
  • 🟒 Testing: all looks good
  • 🟒 Complexity: all looks good
  • 🟒 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click πŸ‘ or πŸ‘Ž on each comment and I'll use the feedback to improve your reviews.

src/App.jsx Outdated
Comment on lines 19 to 24
useEffect(() => {
const storedSettings = getStoredEndpointSettings();
if (!storedSettings) {
setEndpointSettings(getDefaultServer(), getDefaultAppId());
}
}, []);
Copy link

Choose a reason for hiding this comment

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

suggestion: Consider adding error handling around the storage operations

Storage operations can fail due to various reasons (quota exceeded, privacy mode, etc.). Wrap the operations in a try-catch block to gracefully handle potential errors.

Suggested change
useEffect(() => {
const storedSettings = getStoredEndpointSettings();
if (!storedSettings) {
setEndpointSettings(getDefaultServer(), getDefaultAppId());
}
}, []);
useEffect(() => {
try {
const storedSettings = getStoredEndpointSettings();
if (!storedSettings) {
setEndpointSettings(getDefaultServer(), getDefaultAppId());
}
} catch (error) {
console.error('Failed to access storage for endpoint settings:', error);
// Ensure app can still function by using defaults without storing them
const defaultServer = getDefaultServer();
const defaultAppId = getDefaultAppId();
try {
setEndpointSettings(defaultServer, defaultAppId);
} catch (storageError) {
console.error('Failed to store default endpoint settings:', storageError);
}
}
}, []);

@github-actions github-actions bot had a problem deploying to preview January 17, 2025 11:36 Failure
@aum-deriv
Copy link
Collaborator Author

@sourcery-ai review

@github-actions github-actions bot had a problem deploying to preview January 17, 2025 11:39 Failure
@aum-deriv aum-deriv merged commit 100d470 into deriv-com:main Jan 17, 2025
2 of 3 checks passed
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.

2 participants