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

saves the current step of verification form to localStorage #4929

Merged
merged 1 commit into from
Jan 15, 2025

Conversation

maryjaf
Copy link
Collaborator

@maryjaf maryjaf commented Jan 8, 2025

#4924

Summary by CodeRabbit

  • New Features
    • Enhanced step persistence across page reloads by implementing local storage management for verification steps.
    • Improved user experience with step tracking that maintains context between sessions.

Copy link

vercel bot commented Jan 8, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
giveth-dapps-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 8, 2025 11:58am

Copy link
Contributor

coderabbitai bot commented Jan 8, 2025

Walkthrough

The changes modify the VerificationProvider component in the verification context to implement local storage-based step persistence. Two new helper functions are introduced to store and retrieve the current verification step. The component's logic is updated to first check for a stored step in local storage, potentially overriding the default step determination method. A new effect is added to automatically save the current step to local storage whenever it changes.

Changes

File Change Summary
src/context/verification.context.tsx Added storeStepInLocalStorage and getStepFromLocalStorage helper functions
Modified useEffect to prioritize stored step from local storage
Introduced new useEffect to persist current step in local storage

Sequence Diagram

sequenceDiagram
    participant Browser
    participant VerificationProvider
    participant LocalStorage

    VerificationProvider->>LocalStorage: Check stored step
    alt Stored step exists
        LocalStorage-->>VerificationProvider: Return stored step
        VerificationProvider->>VerificationProvider: Set current step
    else No stored step
        VerificationProvider->>VerificationProvider: Determine step from verification data
    end

    VerificationProvider->>LocalStorage: Store current step when changed
Loading

Poem

🐰 A rabbit's tale of steps preserved,
In local storage, context observed!
Reload the page, no context lost,
Our verification path, forever glossed!
Persistent state, a coding delight! 🔍


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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
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/context/verification.context.tsx (2)

53-68: Consider adding expiration and error handling to localStorage operations

The implementation could be enhanced with:

  1. An expiration mechanism to prevent stale data persistence
  2. Error handling for parseInt and localStorage operations
  3. A project-specific key prefix to prevent naming conflicts

Consider this improved implementation:

 const storeStepInLocalStorage = (step: number) => {
   if (typeof window !== 'undefined') {
-    localStorage.setItem('lastStep', step.toString());
+    const data = {
+      step,
+      timestamp: Date.now(),
+      projectSlug: slug
+    };
+    try {
+      localStorage.setItem('verification_lastStep', JSON.stringify(data));
+    } catch (error) {
+      console.error('Failed to store step:', error);
+    }
   }
 };

 const getStepFromLocalStorage = () => {
   if (typeof window !== 'undefined') {
-    const lastStep = localStorage.getItem('lastStep');
-    return lastStep ? parseInt(lastStep, 10) : -1;
+    try {
+      const data = localStorage.getItem('verification_lastStep');
+      if (!data) return -1;
+      
+      const parsed = JSON.parse(data);
+      // Return -1 if data is older than 24 hours or belongs to different project
+      if (Date.now() - parsed.timestamp > 24 * 60 * 60 * 1000 || 
+          parsed.projectSlug !== slug) {
+        localStorage.removeItem('verification_lastStep');
+        return -1;
+      }
+      return typeof parsed.step === 'number' ? parsed.step : -1;
+    } catch {
+      return -1;
+    }
   }
   return -1;
 };

126-131: Optimize localStorage writes with cleanup and debouncing

The current implementation might cause unnecessary writes to localStorage. Consider adding cleanup and debouncing.

Here's an optimized version:

 useEffect(() => {
+  const debounceTimeout = 1000; // 1 second
+  let timeoutId: NodeJS.Timeout;
+
   if (step >= 0) {
-    storeStepInLocalStorage(step);
+    timeoutId = setTimeout(() => {
+      storeStepInLocalStorage(step);
+    }, debounceTimeout);
   }
+
+  return () => {
+    if (timeoutId) {
+      clearTimeout(timeoutId);
+    }
+  };
 }, [step]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8588535 and 91229a0.

📒 Files selected for processing (1)
  • src/context/verification.context.tsx (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (2)
src/context/verification.context.tsx (2)

Line range hint 53-132: Implementation successfully meets PR objectives

The changes effectively implement step persistence using localStorage, meeting the goal of preserving user progress during page navigation or refresh. While there are opportunities for enhancement, the core functionality is solid and well-implemented.


80-85: Verify stored step validity against current form state

The current implementation might restore an invalid step if the form state has changed since it was stored. Consider validating the stored step against the current verification state.

Add validation before using the stored step:

 let lastStep = getStepFromLocalStorage();
-if (lastStep !== -1) {
+if (lastStep !== -1 && lastStep <= menuList.length) {
+  // Ensure the step is valid for current verification state
+  const isStepValid = lastStep === 0 || (
+    projectVerification.emailConfirmed &&
+    lastStep <= findFirstIncompleteStep(menuList, projectVerification)
+  );
+  if (isStepValid) {
     setStep(lastStep);
     return;
+  }
 }

@maryjaf maryjaf self-assigned this Jan 14, 2025
@maryjaf
Copy link
Collaborator Author

maryjaf commented Jan 14, 2025

@kkatusic could you please check this Pr?

@maryjaf maryjaf requested a review from kkatusic January 14, 2025 09:46
Copy link
Collaborator

@kkatusic kkatusic left a comment

Choose a reason for hiding this comment

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

@maryjaf nice job, but it now returns to one step before :(

@maryjaf
Copy link
Collaborator Author

maryjaf commented Jan 15, 2025

@maryjaf nice job, but it now returns to one step before :(

I've tested on this branch "https://giveth-dapps-v2-git-edit-in-socialprofile-page-general-magic.vercel.app/" and it works as expected, could you please add more data about your scenario, Thanks@kkatusic

Screen.Recording.2025-01-15.at.11.17.21.AM.mov

@kkatusic
Copy link
Collaborator

@maryjaf, check my video, after accepting Discord to connect I was returning to previous step. I tested on same link as you share. If you can't get same problem, we can schedule the call and then check it together.

Screen.Recording.2025-01-15.at.10.31.01.mov

@maryjaf maryjaf merged commit 773c6ef into develop Jan 15, 2025
3 checks passed
@maryjaf maryjaf deleted the edit-in-socialprofile-page branch January 15, 2025 12:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

2 participants