We’ll be diving deep into this file from the mern-boilerplate. To learn what Axios is, read here.

Introduction

In this demo, we’ll be assuming that there are already endpoints available. This is not a walkthrough about Express.js nor about creating the api endpoints (see here instead). [TODO insert page link]

We will be performing CRUD operations for a user, meaning we’re building the UI to create, read, update, and delete users through HTTP requests made through Axios.

API

The api/ folder contains Axios implementations to send requests to the backend. The user.ts file contains the CRUD operations, and we will be going in-depth about it.

Let’s take a look at the type definitions in this file

type IdParam = { id: string }
type UserParam = { firstName: string; lastName?: string }

type UserData = { user: IUser }
type UsersData = { users: IUser[] }

We define the types for the parameters for the CRUD functions (IdParam and UserParam) and also the return type from the http requests (UserData and UsersData).

The only problem is that we have to define the return type explicitly, since we can’t import type defs from backend. This is unavoidable, and means that we just have to redefine the types again.

One thing that could be useful is exporting these types. Since these types aren’t used anywhere, I choose not to export them, but I would recommend doing it if it is used.

Axios Instance

Now, let’s take a look at the Axios instance

const UserClient = axios.create({
  baseURL: `${process.env.REACT_APP_SERVER_URL}/api/user`,
  timeout: 1000,
})

The env variable REACT_APP_SERVER_URL should be the base url of your server. If you are doing this locally and following the mern-boilerplate, it would most likely be http://localhost:8080 or whatever port you use. The baseURL field for the Axios instance is the user api endpoint that backend has already set up. See here [TODO insert backend page]

The timeout field is how long Axios would wait for a response before timing out (throwing an error). In this case it is 1000ms (1 second).

Read user(s)

Next up are the CRUD routes. We’ll go over them one by one.

export const getUser = ({ id }: IdParam) => UserClient.get<UserData>(`/${id}`)
export const getUsers = () => UserClient.get<UsersData>('/')