bulletproof-react icon indicating copy to clipboard operation
bulletproof-react copied to clipboard

Reduce or generalize code generated by mutations and queries (API Layer)

Open glauco-proj opened this issue 2 years ago • 1 comments
trafficstars

The mutations and queries used from react-query bring indisputable benefits to the application, in addition separated into a layer / folder, bringing organization.

However, when the system has many similar CRUDs they generate a large volume of code, duplicated and highly dependent of react-query. If react-query changes many in a future release, much of the system will have to be rewritten.

Is there any way or has anyone already applied a way to reduce the code generated by mutations and queries? Any suggestions for abstracting and generalizing the dependency?

I thought of something similar to the one below:

import { useCreate, CreateOptionsType } from '../../../lib/api/create';
import { useUpdate, UpdateOptionsType } from '../../../lib/api/update’;

export const useCreateFinalUse = ({ config }: CreateOptionsType = {}) => {
  return useCreate('final-uses-key', {
    ...config
  });
};

export const useUpdateFinalUse = ({ config }: UpdateOptionsType = {}) => {
  return useUpdate('final-use-key', {
    ...config
  });
};

//and more for other operations

The create and update files will be generic structures, with generic types... any ideas? it's viable?

glauco-proj avatar Jul 28 '23 20:07 glauco-proj

I faced a similar problem at work, but I didn't like the idea of using an abstract hook for some CRUD operation in fear of over-generalization, even if there was code duplication. I'm looking to hear other opinions on this matter.

HasanMothaffar avatar Nov 07 '23 06:11 HasanMothaffar

In the sample app it looks like CRUD, but let's assume you have a more complicated case, which is always the case in a real-world scenario. I would rather have a bit of boilerplate than have an abstraction that I need to extend most of the time anyway. Maybe you can look into this project if you want some abstraction.

alan2207 avatar May 14 '24 07:05 alan2207