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

Use @tanstack/react-query for data fetching #5954

Merged
merged 26 commits into from
Sep 14, 2023

Conversation

HelNershingThapa
Copy link
Contributor

@HelNershingThapa HelNershingThapa commented Jun 28, 2023

This pull request introduces a significant migration in the API fetching logic, replacing the existing implementation with the powerful React Query library. By adopting React Query, we can leverage its declarative approach, efficient caching mechanisms, and automatic data synchronization capabilities, resulting in improved performance and code maintainability. Also, This pull request attempts to resolve #5763, an existing issue related to network error handling.

Landing Page

The app displays hyphens for the stats numbers even after the endpoint API fails. Mentioned here #5749 (review)

  • An error boundary has been introduced when one of the statistic endpoints fails or the component encounters an exception while rendering.
    stats-landing

My Contributions Page

The header profile doesn't show any affiliated organizations if fetching organizations fail.

  • Display fetching error message in the Alert component.
    load-orgs

The teams will keep loading forever if fetching them fails.

  • Display fetching error message in the Alert component.
    my-teams

Project Detail Page

The app crashes or becomes unresponsive when loading questions, comments, or navigating with pagination buttons.

  • Ensured UIs for loading, error, and success states for project's questions and comments section.
    questions-and-comments'

The loading indicator for the contribution timeline section continues to show indefinitely, even after the API has failed.

  • Display an alert component indicating a network error during contribution timeline fetching.
    alert-contributions-timeline

The loading indicator for the contribution timeline section continues to show indefinitely, even after the API has failed.

  • Display an alert component indicating a network error during contributors fetching.
    alert-contributors

Project's Tasks Selection Page

The app displays the "failed to fetch" text when it fails to retrieve the project's summary.

The loading indicator for the contribution timeline section continues to show indefinitely, even after fetching activities for a project fails.

The app crashes when the user contributions endpoint fails.

The app crashes when it fails to load the latest activities.

  • Display an error boundary fallback component when any of them fail.
    task-selection-error

Task Detail Modal

The app does not display a loading indicator when loading comments or activities, and it shows an empty container instead of an error message when it fails to load.

  • Display a loading placeholder component when loading and an alert component when fetching task details fails.
    error-modal

When a comment POST fails, the app does not display any error message to inform the user.

  • Display success and error messages for comment posting. Disable the Comment button during loading and when the textfield is empty.
    comment-sent ssssss

Task Action Page

The app always navigates the user to the tasks page when failing to fetch information about the user's locked tasks, without handling the error.

  • Display error toast message when fetching locked tasks fail; still navigates to the task selection page. Added route level error boundary to the task action page.
    task-action-boundary

The app experiences a forever loading issue on the task action page when failing to fetch the project summary.

When there is a failure to fetch project tasks, the app is currently crashing

  • Display the above error boundary.

When the task history fails, the app provides no UI indication to inform the user of the failure. There is no loading indicator, and the app behaves the same as when there is no error

  • A message will be displayed on the Alert component.

When there is a failure to load priority areas, the app is not currently providing any response in the UI

  • Added an error toast that displays upon clicking the Tasks map button in the iD or RapiD editors and when the API endpoint fails in the JOSM editor.
    toast-priority

When submitting a task fails or when trying to select another task, the app is not currently providing any response in the UI

  • Implemented error toast for all actions: submit task (mapping and validation), stop session (mapping and validation), and split task. The modal error message will only be displayed for the specific error subcode ("too small... ") when splitting a mapping task.
    submit-task

Project Stats Page

When the app fails to load the project summary, the stats page becomes stuck in an indefinite loading state.

  • Added error boundary fallback to the entire page when the app fails to load the project summary
    project-stats-project-summary

If loading project tasks fails, all stat numbers are shown as zero.

  • Display fetching error message in the Alert component. [Data for tasks by status is being used in two sections]
    task-fail

Loading the contributors' section leads to an indefinite loading state.

  • Display fetching error message in the Alert component.
    Screenshot from 2023-07-31 15-53-48

Loading the project timeline leads to an indefinite loading state.

  • Display fetching error message in the Alert component.
    project-timeline

Loading the time statistics section leads to an indefinite loading state.

  • Display fetching error message in the Alert component.
    time-stats

@github-actions github-actions bot added scope: frontend dependencies Pull requests that update a dependency file javascript labels Jun 28, 2023
@HelNershingThapa HelNershingThapa force-pushed the feature/introduce-react-query branch 2 times, most recently from ea46623 to 67705db Compare June 29, 2023 10:59
@HelNershingThapa HelNershingThapa force-pushed the feature/introduce-react-query branch 3 times, most recently from bb70a15 to 6fa841f Compare July 6, 2023 07:45
@HelNershingThapa
Copy link
Contributor Author

@Bonkles, can you or the team provide a review/feedback on this PR?

@sonarcloud
Copy link

sonarcloud bot commented Aug 7, 2023

Kudos, SonarCloud Quality Gate passed!    Quality Gate passed

Bug A 0 Bugs
Vulnerability A 0 Vulnerabilities
Security Hotspot A 0 Security Hotspots
Code Smell A 0 Code Smells

No Coverage information No Coverage information
0.0% 0.0% Duplication

Copy link
Contributor

@d-rita d-rita left a comment

Choose a reason for hiding this comment

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

LGTM. The different parts of the app work as expected. Fetching stats on the home page, the explore page with project fetching (with various filters), the manage section with CRUD operations for teams, projects, organisations, etc., the mapping and validation workflows, contributions and statistics pages.

- Created new instance of Axios that accepts token and locale.
- Utilized react-query useQuery hook to fetch TM system statistics and OSM Stats
…s and User Projects page

- Added a new utility react query hook function called `useProjectsQuery` for handling project fetching in Explore Projects and User Projects pages.
- Implemented `useProjectsQuery` using the existing logic from `useProjectsQueryAPI`, eliminating the need for the useThrottle function.
- Revised the `ProjectsPage` and `UserProjectsPage` components to utilize react-query states.
- Made necessary changes to the `ProjectSearchResults`, `ProjectsMap`, and `ProjectCardPaginator` components to accept appropriate props.
- Updated test cases to reflect the changes and ensure compatibility with the updated functionality.
- Added `useProjectQuery` hook to handle project detail fetching for `ProjectDetailPage` component
- Updated network handler to reflect axios' error response in msw implementation
- Updated test cases to reflect changes and removed unnecessary props in `ProjectDetailPage`
- Added `useCommentsQuery` hook to fetch project's questions and comments, updating the implementation to match the states from the new hook.
- Replaced the existing implementation for posting comments with the `useMutation` hook, eliminating the use of the `useAsync` hook.
- Implemented UI components to display loading and error network states for questions and comments.
- Renamed the function from updateComments to refetchComments for clarity and consistency.
- Replaced the usage of `useFetc`h with the `useProjectContributionsQuery` hook to fetch project contributions in the project detail page. Extracted the logic for fetching project contributions into the `useProjectContributionsQuery` hook.
- Added conditional rendering based on contributors status to handle loading and error states.
- Replaced the usage of `contributors?.userContributions` with contributors directly in the `UserAvatarList` component.
- Replaced the usage of `useFetch` with the `useProjectTimelineQuery` hook to fetch data for project timeline in the project detail page. Extracted the logic for fetching into the `useProjectTimelineQuery` hook.
- Added conditional rendering based on contributors status to handle loading and error states.
- Removed the <ReactPlaceholder> wrapper for the action buttons since there is no need to check the type of `props.project` as it is always an object and is readily available by being passed from its parent component.
- Rendered the action buttons directly without the placeholder, assuming the loading state is handled elsewhere if necessary.
- Replaced the usage of `useFetch` with the `usePriorityAreasQuery` hook to fetch priority area in the task selection page. Extracted the logic for fetching into the `useProjectTimelineQuery` hook.
- A toast message is displayed when fetching priority areas fails.
…d handle error boundaries

- Added `Preloader` component for the loading state in the task selection page.
- Renamed the `Error` component to `ProjectError` for clarity.
- Added an `useEffect` hook to handle navigation to the login page when there is no token.
- Wrapped the `TaskSelection` component with an `ErrorBoundary` and provided `FallbackComponent` for error handling.
- Refactor textSearch validation - instead of using an inline if statement, the code now assigns the result of the textSearch validation to a variable named `isTextSearchValid`. If `isTextSearchValid` is true, the code proceeds to update the selected tasks and retrieve the currentStatus using the `find` array method.
- Removed redundant checks for availability of the project prop.
- Revised `useProjectContributionsQuery` to include additional options for compatibility with both the project detail page and the task selection page.
- Replaced usage of `useFetch` hook with `useActivitiesQuery`, `useTasksQuery`, `useProjectContributionsQuery`, and `useUserTeamsQuery` react-query hooks. Also updated the relevant variables with values from the query hooks.
- Refactored derived states, such as `tasks`, `randomTask`, and `isValidationAllowed`, to be derived from other states, eliminating the need for their own states.
- Updated test cases to reflect the above changes.
- Added the `useTaskDetail` `react-query` hook to fetch task detail. The hook ensures that the task detail is refetched every minute when the modal is open.
- Implemented loading and error states for the task detail comments/activities. When the task detail is being fetched, a loading state is displayed to provide feedback to the user. If there is an error during the fetch process, an error alert is displayed.
- Extracted the `getTaskActionMessage` function from the component and moved it to the bottom of the file.
- Refactored the `TaskHistory` component. Removed the `commentPayload` prop from the component, as it was no longer necessary. Additionally, removed states that were derived from other states and converted them into their own variables. With the integration of react-query, subsequent common requests for fetching task detail are handled automatically, eliminating the need for manual management.
Moves the actions dispatches to the `TaskAction` component, removing it from both the `Editor` and the `RapidEditor` components.
- Added the `useLockedTasksQuery` React Query hook, which fetches the locked tasks of a user. The hook's `cacheTime` option is set to 0, ensuring that the data is always fetched from the server.
- Redirect to the login page when no token is available, instead of displaying the login page on the same route.
- Migrated the codebase to utilize React Query hooks for fetching data, replacing the previous usage of fetch requests.
- Removed the `projectIsReady` prop, as it was determined to be redundant since it always had a value of true.
- Implemented the display of a priority area on the task map.
- Updated the test cases to reflect all the aforementioned changes.
- Refactored the notifications page and bell component to use react-query. Added new hooks `useNotificationsQuery` and `useUnreadNotificationsCountQuery`. Updated the data fetching logic in the notifications page and bell component to utilize react-query's query hooks
- Updated tests to reflect the changes
- Refactored the `PostComment` component to utilize the `useMutation` hook for handling API calls.
- Introduced the `postTaskComment` function to handle the API call for posting a comment.
- Renamed the previous `postComment` function to `postProjectComment`.
- Added the `MessageStatus` component to the `PostComment` component. This component is responsible for displaying error and success states during the post comment process.
- Implemented the disabling of the button in the loading state and when there is no comment in the text field.
- Migrated `src/views/projectStats.js` to use react-query hooks instead of `useFetch`.
- Implemented loading and error states for all sections in the project statistics page, utilizing the `Alert` component.
- Added an error boundary for the project statistics page using the `FallbackComponent` component, specifically to handle failures in loading the project summary.
- Enhanced `useProjectSummaryQuery` and `useTasksQuery` react-query hooks to accept additional options in the definition, allowing different query options when used in various components.
- Introduced the `useProjectStatisticsQuery` and `useOsmHashtagStatsQuery` react-query hooks to fetch project statistics for statistics.
- Relocated the timelineDataError message to /views/messages for better organization.
- Replace the `useFetch` hook with `useUserOrganisationsQuery`.
- Update the rendering logic based on the new data structure returned by `useUserOrganisationsQuery`.
- Show an error message using the `Alert` component if the data fetching fails.
- Modified `useUserTeamsQuery` hook to accept `params` and `otherOptions` as query options instead of `userId` allowing more customizations.
- Adjusted all references to the `useUserTeamsQuery` hook to accommodate the new changes and ensure compatibility with the updated query options.
- Made use of the  `Alert` component to handle scenarios when fetching teams fails.
- Updated existing test cases related to the `useUserTeamsQuery` hook to reflect the modifications made in the hook's behavior and parameters.
- Added error boundaries to enhance error handling on map and validation action pages. The route error boundary now covers locked tasks, project summary, and project tasks. Also  replaces the previous toast implementation for locked tasks.
- Improved API interactions in the `CompletionTabForMapping` and `CompletionTabForValidation` components by migrating all POST requests to utilize the `useMutation hook` from `@tanstack/react-query`.
- Implemented error toasting for failed POST operations. Now, when any POST request encounters an error, an error toast will be displayed. For split operations, the previous modal error message will be shown only if the error `SubCode` matches the specific condition `SmallToSplit`.
- When fetching priority areas encounters an error, an error toast will be displayed.
In the case of a 404 error, present a "Project Not Found" message like before and for the rest of the error while fetching project summary, the fallback error component will be displayed.
@sonarcloud
Copy link

sonarcloud bot commented Sep 14, 2023

Kudos, SonarCloud Quality Gate passed!    Quality Gate passed

Bug A 0 Bugs
Vulnerability A 0 Vulnerabilities
Security Hotspot A 0 Security Hotspots
Code Smell A 0 Code Smells

No Coverage information No Coverage information
0.0% 0.0% Duplication

@HelNershingThapa HelNershingThapa merged commit 669ca25 into develop Sep 14, 2023
3 checks passed
@HelNershingThapa HelNershingThapa deleted the feature/introduce-react-query branch September 14, 2023 10:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
dependencies Pull requests that update a dependency file scope: frontend
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Improving network error handling
2 participants