LibraryProjectGroup / library-project-frontend

Frontend
https://frontend-staging-efilibrary.jrdie.nl/
MIT License
4 stars 0 forks source link

Refactoring frontend #166

Closed swd1tn002 closed 1 year ago

swd1tn002 commented 1 year ago

One thing that would be really good is to go through the tsx files and to turn them into smaller components, ListBooks.tsx for example is about 650 lines long 💀

swd1tn002 commented 1 year ago

ChatGPT suositteli seuraavia toimenpiteitä. Näistä voisi valita yhden tai useammat ja niistä tehdä omat taskinsa:

Refactoring code can be a multi-step process, and it often depends on specific goals and requirements. However, here are some general steps and suggestions to refactor the given code:

  1. Organize Imports: Start by organizing your imports. Group related imports together and remove any unused imports. This will make the code cleaner and easier to read.
import React, { useState, FC, useEffect, useContext, Fragment, useCallback } from "react";
import {
  Paper,
  Typography,
  Button,
  Stack,
  Box,
  Fab,
  Grid,
  Tooltip,
  TablePagination,
  Snackbar,
  IconButton,
  Alert,
  InputLabel,
  MenuItem,
} from "@mui/material";
import { useNavigate } from "react-router-dom";
import { TheContext } from "../../../TheContext";
import {
  fetchAllBooks,
  fetchDeleteBook,
  fetchAllCurrentBorrows,
  // ... (other fetch functions)
  fetchAllBooksCount,
  fetchDeleteUser,
} from "../../../fetchFunctions";
import {
  listBooksDeleteButton,
  listBooksEditButton,
  listBooksLoanButton,
  addBookAddButton as addButton,
  listBooksFavoriteButton as favButton,
} from "../../../sxStyles";
import ToastContainers from "../../../ToastContainers";
import { LOAN_DAYS, RESERVATION_DAYS, MS_IN_DAY } from "../../../constants";
import CountrySpan from "../../CountrySpan";
import OfficeSpan from "../../OfficeSpan";
import "react-toastify/dist/ReactToastify.css";
  1. Component Decomposition: Break down your ListBooks component into smaller, reusable components. This will make the code more modular and easier to maintain. For example, you can create separate components for book rendering and pop-ups.

  2. Use Hooks: You're using a mix of class component state (useState) and function component state (const [page, setPage] = React.useState(0);). Consider using hooks consistently for state management. You've already started using hooks for some state variables, continue doing so for the rest.

  3. Reduce Repetition: There are several repetitive code blocks. For example, the code for rendering buttons (renderLoanButton and renderReserveButton) can be refactored into a single function that takes parameters for the button label and click handler.

  4. Optimize Loops: Instead of using for loops for checking conditions (e.g., bookInCurrentBorrows and bookInCurrentReservations), use array methods like Array.prototype.some or Array.prototype.find for cleaner and more efficient code.

  5. Conditional Rendering: Use conditional rendering to clean up your JSX. If a component or element should only appear under certain conditions, use conditional logic to determine when it should be rendered.

  6. Extract Constants: Extract hardcoded values like the default book cover image URL into constants or configuration files for better maintainability.

  7. Separate Concerns: Ensure that each function or component has a single responsibility. If a function/component is doing too much, consider breaking it down into smaller functions/components.

  8. Remove Unused Code: Remove any commented-out or unused code to declutter the codebase.

  9. Comments and Documentation: Add comments and documentation to clarify the purpose of functions, components, and complex logic.

  10. Error Handling: Implement proper error handling for your async functions to handle potential network errors or exceptions.

  11. Testing: Consider writing unit tests for critical parts of your code to ensure that refactoring does not introduce new bugs.

Remember that refactoring is an iterative process, and it's essential to test your code thoroughly after each refactoring step to ensure it still works correctly. Additionally, follow coding standards and best practices to make your code more readable and maintainable.

swd1tn002 commented 1 year ago

ChatGPT osaa myös auttaa yksittäisten kohtien refaktoroinnissa, kun sille esittää tarkempia kysymyksiä.

Huom! Älkää suoraan kopioiko saamianne koodinpätkiä, koska ne voivat tehdä ihan muuta kuin mitä on tarkoitus. Sen sijaan perehtykää ratkaisuun ja jos se osoittautuu toimivaksi, tehkää muutos itse.

Certainly! You can refactor the bookInCurrentReservations function using the Array.prototype.some method, which checks if at least one element in an array satisfies a given condition. Here's how you can refactor it:

Original bookInCurrentReservations function:

const bookInCurrentReservations = (book: Book) => {
  let inCurrentReservations = false;
  for (let i = 0; i < currentReservations.length; i++) {
    if (currentReservations[i].bookId === book.id) {
      inCurrentReservations = true;
    }
  }
  return inCurrentReservations;
};

Refactored bookInCurrentReservations function using Array.prototype.some:

const bookInCurrentReservations = (book: Book) => {
  return currentReservations.some((reservation) => reservation.bookId === book.id);
};

In the refactored code:

  1. We use the Array.prototype.some method, which takes a callback function as its argument.
  2. Inside the callback function, we check if reservation.bookId matches book.id.
  3. The some method will return true if at least one element in currentReservations satisfies the condition, otherwise, it returns false.

This refactoring simplifies the code and makes it more concise while maintaining the same functionality. It also eliminates the need for manual iteration using a for loop.