DEV Community

Discussion on: How do you handle asynchronous requests in ReactJS?

Collapse
 
cyberhck profile image
Nishchal Gautam

I handle API calls completely differently.
First I don't wrap fetch around something, I use a library @crazyfactory/tinka, it's not popular, but it has functionalities like, adding a default baseUrl, and ability to use middlewares.

I add a few middlewares, like WrapMiddleware which does a .json() on response, I also add a JwtMiddleware which automatically adds JWT to each request, I also use RefreshTokenMiddleware which refreshes jwt when it's expired, I sometimes use MockMiddleware when I just want to play around in frontend and don't want to build backend yet.

Another huge thing I do for production is that, I don't add api calls to my projects, I build a SDK which uses these, so api calls look like this:

const api = Api.getInstance();
const posts = await api.posts.list();
// or:
const response = await api.posts.create({body: ""}); // tserror: title is required

the return type of post.list() is Promise<Post[]>, all API calls are strongly typed.

Now I don't make API calls from components, because they're not supposed to be from there, I make API calls from a side effect layer, I use redux-saga for that.

Collapse
 
potouridisio profile image
Ioannis Potouridis

Do you happen to have any examples on this approach? Seems interesting.

Collapse
 
cyberhck profile image
Nishchal Gautam • Edited

I don't have a running example which you can just clone and start using unfortunately, I do have some projects to point you in that direction:

  • Normally SDKs can be generated if you write your APIs right, just using swagger and using autorest to generate all sdks, every time you update your API, it can automatically publish the sdk to npm.
  • Or you can handwrite your own SDK, like here: github.com/devcurate/sdk (is an example), I've used a lot of automation so I don't have to make a release every time I want to use it.
  • That sdk, accepts an instance of Client which comes from tinka

(I've a project where I didn't create sdk separately, but directly in the project itself, because it had only two endpoints: github.com/cyberhck/EventCheckIn-C...) there I configure everything.

github.com/cyberhck/EventCheckIn-C... here you can see that every time a particular action is dispatched, we perform a side effect.

(side effect can be, when user clicks on a message, clear the message notification icon, or making an api call, (or even make completely different api call according to business logic))