'Request management using services
I noticed that some developers are using so-called "services" to manage front end requests, for example:
const httpService = {
get(url) {
fetch(url).then((response) => {
if (!response.ok) {
throw new Error('error')
}
return response.json()
})
}
}
const getPostService = (url) => { // this is the service
return httpService.get(url).then((json) => json)
}
getPostService('/post')
.then(r => setData(r))
.catch(e => setError(e));
Is there a reason to create multiple services like: getPostService or getUserService, or getDataService, or the implementation is the same if inside the code will do:
httpService.get(url).then((json) => setData(json)).then(e => setErr(e))
Is a reason to create services or they are redundant in my case being enough to fetch data only using httpService without creating many services in my app?
Solution 1:[1]
Your example is strange, and doesn't make a ton of sense to me.
It doesn't look like your getPostService returns any service, it literally just wraps the httpService.get function, with no real benefit.
You can see this even clearer when cleaning up the function from:
const getPostService = (url) => { // this is the service
return httpService.get(url).then((json) => json)
}
To:
const getPostService = url => httpService.get(url);
However, if this function was called getPosts or it returned a useful object that does operations related to posts, it makes a lot of sense.
For example, maybe your PostService kinda looks like this:
class PostService {
getPosts() {}
updatePost() {}
deletePost() { }
}
Now your service has some methods that have useful behavior and that can be re-used. If multiple of your components need a 'list of posts', and if all those components just do HTTP requests, then you need to change all components if you want to change something about how 'lists of posts' are fetched.
Putting this in a central place increases maintainability
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Evert |
