API for adding comments
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:21] API for adding comments. First, let's create a new endpoint on the server. That will allow us to post new comments. Define a new post endpoint app. Post, post, id, that's a named segment, comments. Define a callback, request response. Here we first need to get the post id as a number.
[00:22 - 02:13] Const, post, id, equals a number from request, params, id. Then we add a new comment to the comments array. Comments, push, new object with id that we get using the comments length plus one. It's an even simple way to get automatically incremented field. Then we get the author from request body name. We get the content from request body comment post is the post id and time is less than a minute ago. Now return response send status to one. All right, now we have an endpoint that processes the post requests gets the post id from the URL segment and then creates a new comment and pushes it to the comments array. Let's define an API client function. Inside of the comments folder, create a new file, submit, TS. Here define a new function and export it. The function should be called submit comment. Expert async function, submit comment. It's gonna receive post id, of type entity id name, of type person and comment, of type string. It should return a promise with response return await fetch config base URL slash posts post id comments. We'll need to make this request post method post. We send it the headers content type application JSON char set UTF-8 and attach the body JSON stringify an object with fields name and comment.
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)