G
G
Gimir2021-02-03 19:50:49
React
Gimir, 2021-02-03 19:50:49

Where and how best to store the logic for working with api in a React application?

Good day! I wondered how and where it is better to store the logic of working with api in the project.
I saw different examples: Creating classes for specific endpoints with all the necessary methods, and storing them in a separate file; creating functions for endpoint methods that return promises, and storing in different files for different endpoints, etc.

And what is the best way to do this in terms of scalability and reuse?
Maybe there are links to articles or examples of a well-organized project?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Suntsev, 2021-02-04
@GreyCrew

I can recommend storing in middleware, here is my example of organization .
You create an action map with selectors and addresses and use it in middleware.
The map can be extended with various query parameters and used in the middleware.
UPD.
If you have a modular structure and do not want to litter the entire project with a list from the map, then you can make an api saga with which there would be logic with a map of certain endpoints that are used in a separate module / service

A
antsam, 2021-03-11
@antsam

There are many options that you can use. There is no single right and universally accepted decision.
If the project is in redux, then it is done through middleware. Or thunk, or saga - which are also middleware.
If the question is purely api, then look towards Apollo.
None of the options worked for me. I have an unpopular one.
In my last project, I drew a thick line between UI and business logic. I was preparing an article on this subject, but all hands will not reach to finish it. At least I’ll unsubscribe here)
In short, starting from the root component, I divided everything into actors and UI. The branch with the actors is responsible for the business logic, and the branch with the UI is only for rendering (which is what the react was created for)
. These two layers have a common store (for example, using redux).
The UI layer takes data from the store and changes the state based on user actions.
The actor layer looks at the state change and makes the appropriate changes to the store. Including makes requests to the server and saves the result in the store.
But since I like to divide everything as much as possible into layers, then I took out all the API methods in one more layer and threw them into the actors through the context.
This approach with actors is very convenient, unlike redux middleware, because you can use the functionality of react, namely hooks.
And in order not to confuse actors with UI components, I write them in a slightly different style - without jsx and wrapping them in a specially created react-ghost module (such as "ghost")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question