Frontend API client
Get the project source code below, and follow along with the lesson material.
Download Project Source CodeTo set up the project on your local machine, please follow the directions provided in the README.md
file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.
Lesson Transcript
[00:00 - 00:17] Frontend API client. Now that we've created a server API, we can create a front end API client for that API. Create a new directory, API, and inside of it, create two files. Config is where we export const config.
[00:18 - 00:30] For now, it will only contain the base URL. Base URL equals HTTP, localhost, 4000. This is the base URL of our server. And the second one, summary. T.S.
[00:31 - 00:43] Here we'll fetch the posts and categories. Define and export the fetchPost function. Export async function fetch posts. It's a function returning a promise, containing an array of posts.
[00:44 - 01:00] We fetch them from the config base URL plus posts. Don't forget to import fetch from node fetch package. And after we have the response, we return the JSON that we cast to an array of posts wrapped into a promise.
[01:01 - 01:21] Define another function fetch categories. It's going to be quite similar to fetch posts, but going to fetch categories and return an array of categories. Cast the JSON to a proper type as well. It is important that you import the fetch because when next builds a project, it runs outside of the browser environment.
[01:22 - 01:36] So it won't have to the browser fetch function. Node fetch package provides the fetch function in the node environment. Now we have two functions, fetchPost and fetch categories. And we'll use those functions to fetch and prefetch data for the main page.
This lesson preview is part of the Fullstack React with TypeScript Masterclass course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.
Get unlimited access to Fullstack React with TypeScript Masterclass, plus 70+ \newline books, guides and courses with the \newline Pro subscription.
![Thumbnail for the \newline course Fullstack React with TypeScript Masterclass](/_next/image?url=https%3A%2F%2Fs3.amazonaws.com%2Fassets.fullstack.io%2Fn%2F20220425171607321_CoverImage_FSReactWTypeScript_Masterclas.png&w=3840&q=75)