...

/

Extracting Out a Generic http Function

Extracting Out a Generic http Function

Learn to use fetch function to interact with REST API.

We'll need to use the fetch function in every function that needs to interact with the REST API. So, we are going to create a generic http function that we'll use to make all of our HTTP requests. This will nicely centralize the code that calls the REST API.

Steps to centralize the code that calls the REST API

Let's carry out the following steps:

  1. Create a new file called http.ts with the following content:

Press + to interact
import { webAPIUrl } from './AppSettings';
export interface HttpRequest<REQB> {
path: string;
}
export interface HttpResponse<RESB> {
ok: boolean;
body?: RESB;
}

We've started by importing the root path to our REST API from AppSettings.ts, which was set up in our starter project. The AppSettings.ts file is where we will build all of the different paths that will vary between development and production. Make sure webAPIUrl contains the correct path for your REST API. We have also defined interfaces for the request and ...