Posting data with fetch
In this section, we will create a form that submits a new blog post to our REST API. We will create a function that uses fetch
to post to the REST API. That function will be called in the form’s submit handler.
Creating new blog posts using fetch
We will start by creating the function that sends a new blog post to the REST API. This will use the browser’s fetch
function, but this time, using an HTTP POST
request. Carry out the following steps:
- We will start by opening
types.ts
in theposts
folder and adding the following two types:export type NewPostData = {
title: string;
description: string;
};
export type SavedPostData = {
id: number;
};
The first type represents a new blog post, and the second type represents the data from the API when the blog post is successfully saved.
- Create a new file called
savePost.ts
in theposts
folder and add the following import statement:import { NewPostData...