i have Axios with all the interceptors. then i have api folder and put each function request base on api endpoint inside of it.
for exmaple :
api/user.js
api/posts.js
api/auth.js
and so on ... within the JS files i have multiple get request like this:
export getUsers = ({onSuccess, onError, onDone}) => {
return Axios.get("Smaple/users/url").then(res => {
if ( res && res.data ) {
onSuccess(res.data);
}
}).catch(err => {
onError(err);
}).finally(()=>{
onDone();
})
}
i have multiple function like this one.
then i notice i duplicating myself because body of the then, catch and finally are just like the others.
so is it ok to create a global get request like this below ?
const GET_REQUEST = (URL, {onSuccess, onError, onDone}) => {
return Axios.get(URL).then(res => {
if ( res && res.data ) {
onSuccess(res.data);
}
}).catch(err => {
onError(err);
}).finally(()=>{
onDone(err);
})
}
and then user GET_REQUEST like so:
export getUsers = ({onSuccess, onError, onDone}) => {
GET_REQUEST('Smaple/users/url', {onSuccess, onError, onDone})
}
this makes me think maybe later in future i may handle each of these request differently
and it means my GET_REQUEST must have multiple if and else statements. and i think that is not good.
is this a good practice or not ?
Following one of the Clean Code principles (I highly recommend you the book called Clean Code (Robert C Martin)), your first approach is the correct one. Try to follow the DRY Principle as much as you can, and avoid developing overthinking on how your code should behave in the future. This will aim you to cleaner and more readable solutions.
Your code is always up to be refactored by the time is needed. Do not hesitate to change your code once it is done. But I would let the code with just one function.
Regarding the fact of creating a global function, I would aim to create a class (Connector to your server) and define there this function.