samedi 9 avril 2022

React Hooks - distribution of responsibilities (GRASP)

Introduction

I am implementing the analytics of my react app.

This is the structure of my project:

/
  components/
    Profile/
      EditProfileForm.js

  screens/
    Profile/
      EditProfile.js

  services/
    api/
      profile/
        editProfile.js

  hooks/
    profile/
      useEditProfile.js

The folder 'services/api' contains the code that interfaces with the server, that is, the code that calls my endpoints, parses the responses of my microservices... I mean, the interface/gateway.

I have created UI and Business Logic Hooks... this is an extra layer for cleaning the code of my components, or for executing certain business logic like if the user isn't premium, don't let him edit his profile.

Problem

Now, I am about to track the events of my app... I need to place a code, somewhere, for tracking the profile editions (and the respective errors).

I have decided to create helper methods inside my hooks... but maybe, they should be placed in the api methods...

What do you think? Following the low coupling, high cohesion, and controller principles of GRASP, where should I place this code?

import analytics from  "../../services/api/analytics";

const trackProfileEditionError = (err) => {
   analytics.eventsLogger.EXCEPTION({
     description: err.message ?? "Error editing profile"
     fatal: false,
   });
}

My current solution

I see some of my business logic hooks as controllers (intermediaries between my interface and the algorithm that implements it).

In order to decouple the tracking part from the call to my edit-profile endpoint, I have decided to place the code as a helper of my custom hook. Like this:

/
  components/
    Profile/
      EditProfileForm.jsx

  screens/
    Profile/
      EditProfile.jsx

  services/
    api/
      profile/
        editProfile.js

  hooks/
    profile/
      helpers/
        analytics/
          trackProfileEditionError.js

      useEditProfile.jsx // calls services/api/profile/editProfile.js

Note: I know what a custom hook is... in the code of my custom hooks I have native hooks (useRef, useEffect, useCallback...), so they are not helper/utility functions.

Aucun commentaire:

Enregistrer un commentaire