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(skilavottord): PlateCount is not always provided #16233

Merged
merged 9 commits into from
Oct 3, 2024

Conversation

birkirkristmunds
Copy link
Member

@birkirkristmunds birkirkristmunds commented Oct 2, 2024

TS-922

What

Fix plateCount missing value

Why

The new plateCount field isn’t always returning a value when deregistering the vehicle.

Sometimes I get this:

{
  "message": "Variable \"$plateCount\" of required type \"Float!\" was not provided.",
}

And sometimes it seems that no value is being picked up.

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

  • New Features

    • Introduced a loading state in the Car Details component for improved user experience.
    • Added functionality for dynamic plate count selection with user interaction.
  • Bug Fixes

    • Disabled confirm button during loading to prevent user actions.
  • Refactor

    • Streamlined state management and control flow in the vehicle deregistration process.

@birkirkristmunds birkirkristmunds requested a review from a team as a code owner October 2, 2024 10:39
Copy link
Contributor

coderabbitai bot commented Oct 2, 2024

Walkthrough

The pull request introduces modifications to the CarDetailsBox2 component and the Confirm screen related to vehicle deregistration. New props (plateCount, onPlateCountChange, and isLoading) are added to CarDetailsBox2, while reloadFlag is removed. The Confirm component's state management is updated to include plateCount, and a new function handles changes to this state. The control flow is simplified, enhancing the interaction between these components during the deregistration process.

Changes

File Change Summary
apps/skilavottord/web/components/CarDetailsBox2/CarDetailsBox2.tsx - Added props: plateCount, onPlateCountChange, isLoading to BoxProps.
- Removed prop: reloadFlag from BoxProps.
- Updated component function signature and rendering logic to include loading state and conditional rendering for SelectController.
apps/skilavottord/web/screens/DeregisterVehicle/Confirm/Confirm.tsx - Added state variable: plateCount initialized to 2.
- Added method: handlePlateCountChange for updating plateCount.
- Removed reloadFlag and related logic, replacing it with a direct response to query completion.
- Updated CarDetailsBox2 component to accept plateCount and onPlateCountChange props.

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • veronikasif

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai 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
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: 1

🧹 Outside diff range and nitpick comments (5)
apps/skilavottord/web/screens/DeregisterVehicle/Confirm/Confirm.tsx (5)

103-107: LGTM! Consider using a named constant for the initial plate count.

The addition of the plateCount state and its handler function aligns well with the PR objective. This change should help address the issue where plateCount is not always provided.

Consider defining the initial plate count as a named constant at the top of the file or in a constants file. This would improve maintainability and make it easier to adjust if needed in the future. For example:

const INITIAL_PLATE_COUNT = 2;

// ...

const [plateCount, setPlateCount] = useState<number>(INITIAL_PLATE_COUNT)

139-143: LGTM! Consider using optional chaining for improved readability.

The modified useEffect hook simplifies the control flow and aligns well with React best practices. It correctly sets the vehicleReadyToDeregisteredQueryCompleted state based on the query result.

Consider using optional chaining to simplify the condition and improve readability:

useEffect(() => {
  if (data?.skilavottordVehicleReadyToDeregistered) {
    setVehicleReadyToDeregisteredQueryCompleted(true)
  }
}, [data])

This change makes the code more concise while maintaining the same functionality.

🧰 Tools
🪛 Biome

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


164-173: LGTM! Consider extracting the condition to a named function for improved readability.

This useEffect hook appropriately sets the plateCount to 0 based on specific vehicle traffic conditions. It aligns well with the PR objective of handling cases where plateCount might not be provided.

To improve readability and maintainability, consider extracting the condition into a named function:

const shouldSetPlateCountToZero = (trafficData) => 
  trafficData &&
  trafficData.outInStatus.toLocaleUpperCase() === 'OUT' &&
  trafficData.useStatus !== UseStatus.OUT_TICKET;

useEffect(() => {
  if (shouldSetPlateCountToZero(vehicleTrafficData)) {
    setPlateCount(0)
  }
}, [vehicleTrafficData])

This change would make the code more self-documenting and easier to understand at a glance.


Line range hint 1-358: Consider refactoring for improved code organization and reusability.

The overall structure of the component follows React and NextJS best practices, with appropriate use of hooks and state management. However, there are opportunities for improvement:

  1. Extract API calls and related logic into custom hooks (e.g., useVehicleData, useTrafficData).
  2. Consider creating a separate component for handling loading and error states.
  3. Extract form-related logic into a custom hook (e.g., useDeregistrationForm).

These refactoring suggestions could enhance code organization, improve reusability, and make the component easier to test and maintain. For example:

// Custom hook for vehicle data
const useVehicleData = (id) => {
  // ... useQuery logic for SkilavottordVehicleReadyToDeregisteredQuery
  return { vehicle, loading, error };
};

// Custom hook for traffic data
const useTrafficData = (id, shouldFetch) => {
  // ... useQuery logic for SkilavottordTrafficQuery
  return { trafficData, loading, error };
};

// In the component
const { vehicle, loadingVehicle } = useVehicleData(id);
const { trafficData, loadingTraffic } = useTrafficData(id, vehicleReadyToDeregisteredQueryCompleted);

Would you like assistance in implementing these refactoring suggestions?

🧰 Tools
🪛 Biome

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


Line range hint 1-358: Consider leveraging Next.js SSR or SSG features for improved performance.

While the component makes good use of Next.js's useRouter for client-side routing, there might be opportunities to further optimize the application using Next.js-specific features:

  1. If the vehicle data doesn't change frequently, consider using getStaticProps and getStaticPaths for static generation of pages for each vehicle.
  2. For more dynamic data, getServerSideProps could be used to fetch initial data on the server, potentially improving initial load time and SEO.

Here's an example of how you might implement getServerSideProps:

export async function getServerSideProps(context) {
  const { id } = context.params;
  const client = initializeApolloClient();
  
  await client.query({
    query: SkilavottordVehicleReadyToDeregisteredQuery,
    variables: { permno: id },
  });

  return {
    props: {
      initialApolloState: client.cache.extract(),
    },
  };
}

This approach could potentially improve the initial page load time and SEO. Would you like assistance in implementing these Next.js-specific optimizations?

🧰 Tools
🪛 Biome

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4d38b65 and 8cba627.

📒 Files selected for processing (2)
  • apps/skilavottord/web/components/CarDetailsBox2/CarDetailsBox2.tsx (4 hunks)
  • apps/skilavottord/web/screens/DeregisterVehicle/Confirm/Confirm.tsx (5 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
apps/skilavottord/web/components/CarDetailsBox2/CarDetailsBox2.tsx (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/skilavottord/web/screens/DeregisterVehicle/Confirm/Confirm.tsx (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
🪛 Biome
apps/skilavottord/web/screens/DeregisterVehicle/Confirm/Confirm.tsx

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (6)
apps/skilavottord/web/screens/DeregisterVehicle/Confirm/Confirm.tsx (2)

305-307: LGTM! Props update improves component interaction.

The addition of plateCount, onPlateCountChange, and isLoading props to the CarDetailsBox2 component enhances its functionality and user feedback. This change aligns well with the PR objective of handling plateCount more effectively and provides better control over the component's state.

The use of loadingTraffic for the isLoading prop is a good practice for indicating the loading state to the user.


350-352: LGTM! Improved user experience by disabling button during loading.

Disabling the confirm button when loadingTraffic is true is an excellent UX improvement. This prevents users from submitting multiple requests while data is being loaded, potentially avoiding race conditions or duplicate submissions.

This change aligns well with React and NextJS best practices for handling loading states and enhancing user interaction.

apps/skilavottord/web/components/CarDetailsBox2/CarDetailsBox2.tsx (4)

8-8: Import of LoadingDots component is appropriate

The addition of LoadingDots from @island.is/island-ui/core aligns with its usage in the loading state of the component.


37-39: New props added to BoxProps are appropriate

The props plateCount, onPlateCountChange, and isLoading are correctly added to the BoxProps interface, ensuring type safety and proper functionality within the component.


51-53: Props are correctly destructured in the component

Destructuring onPlateCountChange, plateCount, and isLoading from the component props makes them accessible for use within the component logic.


123-127: Loading state implementation enhances user experience

The conditional rendering based on isLoading to display a loading indicator improves the user interface by providing feedback during data fetching processes.

Copy link

codecov bot commented Oct 2, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 36.92%. Comparing base (9af30c0) to head (2bcb622).
Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16233      +/-   ##
==========================================
- Coverage   36.93%   36.92%   -0.01%     
==========================================
  Files        6781     6781              
  Lines      140002   140007       +5     
  Branches    39809    39857      +48     
==========================================
+ Hits        51703    51704       +1     
- Misses      88299    88303       +4     
Flag Coverage Δ
api 3.37% <ø> (ø)
application-system-api 41.64% <ø> (ø)
application-ui-shell 21.29% <ø> (ø)
judicial-system-backend 55.24% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

see 5 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 9af30c0...2bcb622. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Oct 2, 2024

Datadog Report

All test runs 42c55eb 🔗

4 Total Test Services: 0 Failed, 4 Passed
➡️ Test Sessions change in coverage: 8 no change

Test Services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
api 0 0 0 4 0 2.64s 1 no change Link
application-system-api 0 0 0 120 2 3m 58.82s 1 no change Link
application-ui-shell 0 0 0 74 0 35.24s 1 no change Link
judicial-system-backend 0 0 0 20990 0 21m 34.97s 1 no change Link

@birkirkristmunds birkirkristmunds added the automerge Merge this PR as soon as all checks pass label Oct 2, 2024
Copy link
Member

@veronikasif veronikasif left a comment

Choose a reason for hiding this comment

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

lgtm

@kodiakhq kodiakhq bot merged commit 37cd47a into main Oct 3, 2024
42 checks passed
@kodiakhq kodiakhq bot deleted the fix/skilavottord-plate-count-missing branch October 3, 2024 10:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
automerge Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants