38
loading...
This website collects cookies to deliver better user experience
FancyUserCard
example. If some things would be hard to understand feel free to check the detailed step-by-step path.AxiosInstance
that is configured to work with /users
API branch and our code becomes modular;HttpClient
so we could have as many implementations as we need. It works if we have different HTTP clients like axios
, fetch
, ky
and if we will need to migrate from one to another we would simply need to rewrite our HttpClient
implementation in one place and it will be applied automatically in any place where we use our service;axios
.get<User>(`https://api.fancy-host.com/v1/users/${this.userId}`)
.then((response) => {
this.user = response.data;
})
.catch((error) => {
console.error(error);
});
data()
directly and use global axios
which forces us to type more code for setting the request configuration.then
syntax to async
/await
;axios
instance;Class
.userId
as input parameter and return user
object if the call was successful:export function getUser(userId: number) {
axios
.get<User>(`https://api.fancy-host.com/v1/users/${userId}`)
.then((response) => {
return response.data;
})
.catch((error) => {
console.error(error);
});
}
User
. We just need to specify the userId
and we're ready to go.user
you probably want to get information about posts or comments related to user, right? Sometimes you want to perform requests in parallel and it can be really tricky if we're talking about .then
implementation. So why won't we make it better?export async function getUser(userId: number): Promise<User | undefined> {
try {
const { data } = await axios.get<User>(`https://api.fancy-host.com/v1/users/${userId}`);
return data;
} catch (error) {
console.error(error);
}
}
await
to stop our code from running until the API call finishes. remember that you're able to use await
only inside the async
function.const axiosInstance = axios.create({
baseURL: "https://api.fancy-host.com/v1/users"
});
export async function getUser(userId: number): Promise<User | undefined> {
try {
const { data } = await axiosInstance.get<User>(`/users/${userId}`);
return data;
} catch (error) {
console.error(error);
}
}
/users
API branch will change, you could simply rewrite it in the instance configuration and it will be applied to every call made using this AxiosInstance
. Also, now you could use something called Interceptors which allows you to make some additional changes to requests/responses or perform logic when a request is made or response is back. Check out the link to get more details!data
and error
from our API call. You could also return as many things as you need (if you need them, right?):export type APIResponse = [null, User] | [Error];
export async function getUser(userId: number): Promise<APIResponse> {
try {
const { data } = await axiosInstance.get<User>(`/${userId}`);
return [null, data];
} catch (error) {
console.error(error);
return [error];
}
}
created()
callback:async created() {
const [error, user] = await getUser(this.selectedUser);
if (error) notifyUserAboutError(error);
else this.user = user;
}
notifyUserAboutError
method. Elsewise, if everything went okay, you could simply put the user object into your Vue
component and render fresh information.400 Bad Request
or 401 Unautorized
in case of failed request or if you want to get some response headers if everything was okay), you could add an object in your method return:export type Options = { headers?: Record<string, any>; code?: number };
export type APIResponse = [null, User, Options?] | [Error, Options?];
export async function getUser(userId: number): Promise<APIResponse> {
try {
const { data, headers } = await axiosInstance.get<User>(`/${userId}`);
return [null, data, { headers }];
} catch (error) {
console.error(error);
return [error, error.response?.status];
}
}
async created() {
const [error, user, options] = await getUser(this.selectedUser);
if (error) {
notifyUserAboutError(error);
if (options?.code === 401) goToAuth();
if (options?.code === 400) notifyBadRequest(error);
} else {
this.user = user;
const customHeader = options?.headers?.customHeader;
}
}
Class
and its constructor
.export class UserService {
constructor(private httpClient: AxiosInstance) {}
async getUser(userId: number): Promise<APIResponse> {
try {
const { data } = await this.httpClient.get<User>(`/${userId}`);
return [null, data];
} catch (error) {
console.error(error);
return [error];
}
}
}
const axiosInstance = axios.create({
baseURL: "https://api.fancy-host.com/v1/users"
});
export const userService = new UserService(axiosInstance);
AxiosInstance
and provide access only thru your service public API.