I am working on building an api service for a react native app and I am curious what the difference is between a function that sets up instances and then returns an object with closures around the api functions like this:
export default AuthApiService = (bearerToken) => {
const instance = axios.create({
baseURL: `http://${BASE_URL}`,
timeout: 5000,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${bearerToken}`
}
})
const signup = async (email, password) => {
try {
const response = await instance.post(`/users`, {
email,
password
})
return response.data
} catch (err) {
console.log('error in signup api call', err, err.response)
throw err
}
}
const facebookLogin = async () => {
try {
} catch (err) {}
}
return {
signup,
facebookLogin
}
}
and a class that creates the object with the constructor syntax and has direct access to the methods of the object like this:
export default class AuthApiService {
constructor(bearerToken) {
this.instance = axios.create({
baseURL: `http://${BASE_URL}`,
timeout: 5000,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${bearerToken}`
}
})
}
signup = async (email, password) => {
try {
const response = await this.instance.post(`/users`, {
email,
password
})
return response.data
} catch(err) {
console.log('error in signup api call', err, err.response)
throw err
}
}
facebookLogin = async () => {
try {
} catch(err) {
}
}
}
In javascript class syntax basically just a function that creates an object with a different prototype?
Also if you could give opinions about which approach is "better"?
Thanks