DEV Community

Cover image for React: Writing a custom API hook

React: Writing a custom API hook

Patrick R on August 20, 2019

Let's write a handy custom react hook to take care of the usual API logic we've all written time and time again. Introduction After a c...
Collapse
 
diogomqbm_ profile image
Diogo Mafra • Edited

Why did you decided to use APIService abstraction as a class? Couldn't you make an object with each ajax magic on it? That way you could follow your functional approach. Congratz on the post! Awesome abstraction, ty for sharing!


const APIService = {

  loadUsers: async () => {
     // ajax magic
  },

  loadUsersById: async (id) => {
     // ajax magic
  }

}

export default APIService

Collapse
 
patrixr profile image
Patrick R

Valid point, in part a force of habit, and in another I do have a tendency to inherit base service classes, as seen here. That part kinda got lost as I was trying to simplify things.

Glad you like the hook :)

Collapse
 
marcoscosta profile image
Marcos Costa

Very nice approach Patrick, I'll definitely give it a try, using @diogomqbm_ suggestion as well.

Collapse
 
habelfoc profile image
Habel Justin

you got hooked!

Collapse
 
delimanicolas profile image
Nicolas Lima

Nice post! I'll definitely adopt pieces of your structure. @diogomqbm_ I will use your approach as well.

Collapse
 
robflowk profile image
Robin Wloka

this is a great way of fixing a very common problem i've seen so many times. I really like your approach and i think i'll try it in my current react project.
Hooks are such a blessing.

Collapse
 
patrixr profile image
Patrick R

Hooks are a blessing indeed ! Glad you like it :)

Collapse
 
ahmetozalp profile image
Ahmet

all code shared gist pls...

Collapse
 
patrixr profile image
Patrick R

The entirety of the code is in the article. It's a single function :)

Collapse
 
rafaelfigueiredol profile image
Rafael Figueiredo Gomes Luz • Edited

Hi Patrick! Thanks for sharing this knowledge. I would be glad as well to see this at github. I'm having some problems trying to replicate this and split to use with imports.

Thread Thread
 
patrixr profile image
Patrick R

Thanks Rafael !

Here's a link to this hook on Github.
Cheers :)

Collapse
 
jivkojelev91 profile image
JivkoJelev91

Nice article. I would like to see a custom hook with post request. :(