Up & Running with JSON Server (part 2)
Skills:
API Design80%
Key Takeaways
Uses JSON Server to order and sort data, make POST and DELETE requests, and perform full-text searches
Full Transcript
so when we make a get request to get a certain resource for example posts then json server returns us a data set all of these things right here in a specific order and that default order is based on the id property so we see the id of one first and then the id of three last it goes in order and that's why we see over here the id of one two and three that's the default audit that we get data back in now sometimes we might want to order things differently so we can do this by tacking on some extra parts to the end point right here that we send a request to and we use query parameters to do that so what i'm gonna do over here is add on a question mark first of all and then a property called underscore sort and this is gonna be a sorting order now remember i said the default sorting order is by id but you can tell json server to sort the data that it gets by any of these different properties so for example i could sort it by likes instead so if i say sort is equal to links which is the property name i'm going to save that and preview again this time we get it in a different order this is going to be the lowest likes 15 then 20 and then 30. so the default order is to go from the lowest to the highest that was a bit like id it goes from one until the highest number if we want to reverse this to show the blog with the most likes at the top we can just say and to tack on another parameter and it's going to be underscore order and we can set that equal to descending desc so if i save this now and preview we can see now the one with the most likes is at the top and the one with the least amount of likes is at the bottom pretty simple right so we can just tack on these different parts to the query parameters so we have underscore sort to say what property we want to sort by and underscore order to say whether it should be ascending which is the default value or descending now we can sort by any property that we like if we do it on a string it's going to sort them alphabetically but i think it makes sense in our case to sort it by likes so that the most liked is at the top so next up i want to add new posts to the database file over here by going to the add a new blog page the create page adding in a blog title a blog body and then clicking this thing right here so in order to do this we need to send a post request to the json server so let's go now first of all to create.js and what i'd like to do is get a handle of this form right here so we'll use the query selector to do that i'm just going to paste this in so query selector and we're grabbing the form on this page and storing it in this constant right here the next thing we want to do is attach an event listener to this form and that event is going to be the submit event so let me paste this in we take the form add event listener submit events and we're calling a function right here called create post now this time around we are not putting this inside an anonymous function and that's because i do want to take in the event object as an argument automatically into this function so let's create the function const and then create post and we're going to set that equal to an async function we're taking the event object this time that we automatically get when we invoke this function and then the first thing we want to do is prevent the default action now the default action when we click on this is that the page reloads i don't want that so i'm going to say e dot prevent default in order to do this so now if i save this and come over here and click on create it's not going to refresh the page all right so that's why i wanted the event object inside this function secondly i want to create an object which is going to represent the new record or document that we're essentially going to save to this post resource so an object which looks a bit like this so let me do that by saying const and i'm going to call it doc for document but you can call it what you will and set this equal to an object now the title is going to be whatever user types in this field and the body is whatever they type in this field now we can access those by using these name attributes right here i gave the input name of title and the text area and name of body so we take the form which we already have a handle on and then we say whatever the name attribute is so in our case title so dot title and that gets us that input field then we want the value of that input field and we're going to do the same for the body so that is going to be the form dot body and then the value of that now we also oops it shouldn't be value of just value we also want likes and we're going to start off each new record or document as xero likes we don't add an id and the reason for that is that json server is automatically going to add an id to it that's not already been taken so it will apply an idea for the next id available so we have the document now we want to make a request a post request to a specific endpoint and the end point to make a post request to a resource is just forward slash the resource so let me say here awaits and then we're going to use a fetch request and this is going to go to this end point right here so let me copy that and paste it in and this time we need to pass in a second argument which is an object because it's in here that we say the method of the type of request so this is going to be a post request meaning we're sending data now we need to apply a body property which is going to be the data we send now we can't just send a javascript object that's not the way it works we can't send that between server and clients we have to pass a json string so we can say in javascript json.stringify and then pass in an object which is going to be the doc to turn this into json and that is the data we're going to send okay so it's going to send this to this endpoint json server is going to look at this and say okay i'm going to add this new document that you have in json format into this post resource so after that what do i want to do once this is complete well i want to relocate that user back to the home page once it's been saved so i'll take the window object then say dot location then dot replace and then the url i want to go to which is just forward slash or it could be forward slash index.html it doesn't really matter and that is going to go to the home page once this is done okay so let's give this a whirl i'm going to now add in a new blog title i'll just say mario kart live review i've not got this yet but i do want it and i'm going to copy all of this stuff right here and paste it in and create and now we go back to all blogs there is some kind of error i think let's take a look at what that is it says it cannot read property slice of undefined so i might have made some kind of error title body likes let me take a look in the database file if i go down we can see it has an idea for but nothing else so something is going wrong okay and i think it's because i've not added on the headers property right here we have to say headers and the content type to say that we're sending jason so make sure you have this on then i'm going to save it i'm going to go back to the database file and delete that record save it and then go back over here go to add new blog and we'll say mario kart live review again let me copy all this ninja ipsum a second time paste it in create cool and now it's working so we just needed to say over here when we make that post request the headers and the content type totally forgot about that school by error okay so that my friends is how we send a post request to this endpoint that json server gives us to add new data to the database file and we can see that right here and it takes up the next available id next i'm going to show you how to delete items from the data so currently if we click on read more we see all the details for that particular blog what i'd like to do is add a delete button at the bottom and when we click that we send a delete request to an endpoint provided by json server for that resource and that particular item to delete it so the first thing i'm going to do is add a button to the details html page and if we go down here i'll create that at the bottom so button and then i'll just say delete like so and what i want to do is give this a class of button now we need to get a handle of this inside the javascript file and attach an event listener to it so let me go to details.js and i'm going to paste this in so i've called this constant delete button and we've used query selector to get the delete class which is that button right there so now we need to add an event listener to this i'll grab the delete button say dot add event listener and we want to add a click event listener to it now this callback function is going to be in line so i'm just going to define it here instead of creating a new one like we did with render details but it is going to be asynchronous like so so let me say async we're going to take in the event object i don't think we'll use it but let's take it in anyway and then inside here we want to send a fetch request to delete this particular post now to do that we need to send the request to forward slash posts forward slash the id of whatever post we want to delete now we have that id right here remember we grabbed it before when we said new url search params and passed in this thing right here and then said get the id so i have access to this id and i can just say const response is equal to await and then fetch and inside here first of all let's paste in this thing so let me grab this and copy it and paste that in then it's going to be forward slash plus the id that we have for this particular post remember that's right here okay so now we're sending a request to this endpoint but we also need to pass in a second argument which is that object to say the method is going to be delete and that's all there is to it that is going to send a delete request to this endpoint json server is going to look at that and it's going to find the post with that id right here and remove it from this file so after i've done that what i'm going to do is relocate the user to the home page because then if we delete it well this post no longer exists so we should redirect them to the home page so to do that i'll take the window object then i'm going to say location and then dot replace and then we're going to go to just forward slash it could be forward slash index.html as well it doesn't matter any of those two and that is going to redirect us so fingers crossed this all should work and you can see right now this doesn't exist but what i'm gonna do is let me just check this is all correct i'm going to go to one of these posts okay we don't see all of the data something has gone wrong let me see here right and i figured it out it was because i gave this a class a button not delete which was stupid of me so now we're grabbing remember the delete class and we're attaching the event listener to that okay so now fingers crossed hopefully this will work okay so if we click on delete this is new course coming soon delete it it redirects us to the home page and now we can't see that blog awesome let's try another one let's go to mario kart live review delete that awesome this is working and let's just check our db.json file yep those two blogs have gone okay so finally i want to show you how to do a text search so imagine now we had a search bar at the top over here and the user can search our blog for a term how can we then send a request to the json server to send us all posts which contain this search term well first of all let's create that search form go to the index page over here and what we'll do is create it underneath the nav so let's create a form and get rid of the action but i will give this a class of search like so and inside this form i'm going to do an input and it's type text but i want to give this a name attribute so we can grab it easily later and that is going to be term we'll also give this a placeholder and set that equal to search term okay so now if a user enters into this and presses enter then it's going to submit the form that fires a submit event on this form so first of all we need to grab this form from this index file and then we need to add an event listener to that which is going to listen for the submit event and in that submit event handler we need to query the data for that particular term so let's first of all get a reference to the search form and that is the search class right here okay so we have that and then down here i'm going to attach an event listener to that so i will say search form dot add event listener it's going to be a submit event and then this is going to fire a function and i'm going to take in the event object and inside this function i'm going to first of all say e dot prevents default so that it doesn't refresh the page and then underneath that i want to grab the data that contains that search term right and then when i have that data i want to output it the same way as we do here so we get all of those posts and we cycle through them and create a template for each one of them so what i really want to do is actually run this function again but slightly alter this when we submit this search form so i'm going to say render posts like this right but i'm going to pass in an argument right here and that argument is going to be the search term now to get that search term we can say search form dot and then it was term that was the name attribute remember right here and then we want the value so dot value like so so we're passing in that text value whatever the user types and in fact we'll trim it so we'll say dot trim to remove any white space so we're passing that in now and we have that right here now when we fire this function we're not always going to have this term sometimes it's not going to be defined because when the page first loads and we call render posts we're not passing in a search term then we just want all of the posts and in that case this is going to be undefined so we want to check does this term have a value if it does have a value let's append something to this so that we can search the data for that term so i'm going to do a simple if check right now i'm going to come under this and say if and then term then we'll do something so if this is undefined then whatever is inside this block won't fire if it has a value if we pass something in then it will fire and at that point i'm going to take the uri and i'm going to plus equal something to it so add something to the end now the way we search for something is by using the q parameter or the q key so i'm gonna say and first of all because we're adding on another query parameter like we do here and then we say q and then we set it equal to the search term so i'm gonna output that using a template string so let's delete the normal quotes and replace this with a template string quote and we're going to output the term so let me paste that in and now if we have a term we're just appending this q equals the term to the end of it and what's going to happen is jason's server is going to see that and it's going to look through all of our posts all of the content the title and the body for that search term if it is there inside the title or the body then it's going to add that document to the array that it eventually returns to us the data set if it's not then it's not going to add it to it so we only then get back the items that have that term inside them so let's give this a whirl and remember if there's no term when we first load the page this is not gonna fire and we're just sticking with this so let's save it and let's give this a whirl i'm going to just say blog because i can see that that's right here and i think it's the only instance of block so let me press enter and now we can see we just get back this one results if i delete this and press enter now there's no search term and so we get back all of them let me look for something else i'm going to say is there a word that is in both of them so two we'll do two now this might return more than just these two and it does because inside the body it probably says two i tell you what let's say net press enter and this time we get back this one okay so that is how we search our data using json server so hopefully now you can see how easy it is to set up a local json server for testing prototyping and learning now i use this a lot in my projects and tutorials sometimes because it's just really easy to set up and run with definitely check out the docs if you want to find out more about how to use advanced features such as pagination and data relationships and that link is going to be down below in the description so then my friends i really really hope you've enjoyed this series and if you have enjoyed it please don't forget to share subscribe and like that really means a lot and it helps out an enormous amount and if you do want to join the course and support the channel you can do by clicking the join button on the channel home page or underneath the video or right down below you also get a little cool ninja badge next to your name in the comments for that and it's 99 pence or cents per month and i've also created several premium in-depth courses on udemy so the first one is modern javascript the second one is d3 and firebase and the third one is vue.js and firebase so if you want to take one of those all the links with the discounts automatically applied to them are going to be in the video description down below so again thanks so much for watching and i'm going to see you in the very next course you
Original Description
In this JSON Server tutorial we'll see how to order & sort data with our requests, how to make POST & DELETE requests & also how to make full-text searches.
🐱👤🐱👤 JOIN THE GANG -
https://www.youtube.com/channel/UCW5YeuERMmlnqo4oq8vwUpg/join
----------------------------------------
🐱💻 🐱💻 My Udemy Courses:
+ Modern JavaScript - https://www.thenetninja.co.uk/udemy/modern-javascript
+ Vue JS & Firebase - http://www.thenetninja.co.uk/udemy/vue-and-firebase
+ D3.js & Firebase - https://www.thenetninja.co.uk/udemy/d3-and-firebase
🐱💻 🐱💻 Course Files:
+ https://github.com/iamshaunjp/json-server-tutorial
🐱💻 🐱💻 Helpful Links:
+ Async JavaScript Course - https://www.youtube.com/watch?v=ZcQyJ-gxke0&list=PL4cUxeGkcC9jx2TTZk3IGWKSbtugYdrlu
+ Modern JavaScript Course (free version) - https://www.youtube.com/watch?v=iWOYAxlnaww&list=PL4cUxeGkcC9haFPT7J25Q9GRB_ZkFrQAc
+ JSON Server on NPM - https://www.npmjs.com/package/json-server
+ Get VS Code - https://code.visualstudio.com/
🐱💻 🐱💻 Social Links:
Facebook - https://www.facebook.com/thenetninjauk
Twitter - https://twitter.com/thenetninjauk
Instagram - https://www.instagram.com/thenetninja/
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Net Ninja · Net Ninja · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
GraphQL Tutorial #5 - Express App Setup
Net Ninja
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
GraphQL Tutorial #8 - Root Query
Net Ninja
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
GraphQL Tutorial #12 - Author Type
Net Ninja
GraphQL Tutorial #13 - Type Relations
Net Ninja
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
GraphQL Tutorial #18 - Mutations
Net Ninja
GraphQL Tutorial #19 - More on Mutations
Net Ninja
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
GraphQL Tutorial #23 - Create React App
Net Ninja
GraphQL Tutorial #24 - Book List Component
Net Ninja
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
GraphQL Tutorial #28 - Add Book Component
Net Ninja
GraphQL Tutorial #29 - External Query File
Net Ninja
GraphQL Tutorial #30 - Updating Component State
Net Ninja
GraphQL Tutorial #31 - Composing Queries
Net Ninja
GraphQL Tutorial #32 - query variables
Net Ninja
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
GraphQL Tutorial #34 - Book Details Component
Net Ninja
GraphQL Tutorial #36 - Styling the App
Net Ninja
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
Updated Vue & Firebase Course (Udemy)
Net Ninja
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja
More on: API Design
View skill →Related Reads
📰
📰
📰
📰
Inside the Wayfair Frontend SDE-2 Interview: A Complete Breakdown
Medium · Programming
I Spent Two Years Maintaining a React SPA. HTMX Rebuilt It in a Week
Medium · Programming
The 5 Levels of Front End Engineering (And Where Most Developers Get Stuck)
Medium · Programming
Browser-Based PDF Editing with Vue 3 and pdf-lib
Dev.to · sunshey
🎓
Tutor Explanation
DeepCamp AI