Material UI Tutorial #9 - Using JSON Server

Net Ninja · Beginner ·🌐 Frontend Engineering ·5y ago

Key Takeaways

Uses JSON Server to interact with a JSON file and create a REST API endpoint

Full Transcript

okay then so now we're at the point where we want to start working with a bit of data notes in our case now we could just work with local state in our components but that means that every time we refresh the page it's going to reset our data to that initial state from our component so instead what we'll be doing is working with a json file to store our data and using json server to interact with it so json server basically wraps a json file with rest api endpoint so that we can fetch data inside that json file using a get request or add data to it using a post request etc so it's really good for testing and prototyping so that we don't have to worry about server side logic or databases now i don't want to get bogged down with the ins and outs of jason's server in this lesson so if you want to learn more about it i've got a mini playlist on this channel all about jason's server the link to that is going to be down below so feel free to check it out but the first thing we need to do is create a new file and that is going to be the file to store our data in it so it's going to be a json file and typically what i do is create a folder in the root directory called data and then our json file is going to go inside here so i'll call this db.json db stands for database but you can call it what you want it really doesn't matter and this is where all of our data is going to be stored now rather than me write out all of this json from scratch i'm just going to paste this and you can get this from my repo by the way and woohoo all you need to do is select the correct branch which is lesson 9 from the branch drop down and just find the db.json file so you can grab it all from there but anyway now we have our json and the way json server works is that it looks at this json and any top level property it sees as a resource so in our case we have one top level property called notes and it sees that as a particular resource in our json file and it sets up end points to interact with that resource so i could get all of the notes for example or i could add to the notes so inside the notes array we have three objects each one is a note and each one has a title it has details which is just dummy text it has a category and this is one of the categories we set up before it could be reminders work to do's or i forgot what the other one was let me have a look money so they're the different categories and also each one has a unique id and this id is going to be used by react when we cycle through this data later on and output it to the screen so that is our data file right there the next thing you need to do is install json server onto your computer for this to work so in order to do that you can type npm install hyphen g to install it globally json oops if you can spell it that is json hyphen server and press enter this will install it globally on your computer for you i've already done that so we don't need to do it again but once it's installed the next thing we want to do is run json server and tell it to watch this file right here so we can interact with it so to do that we say json hyphen server like so then double dash watch and then we need a path to this particular file from where we are right here so that's into the data folder forward slash db.json and then i'm going to specify what port to run these endpoints on so i'm going to say double dash port and then we'll run it on port 8000 so press enter and this is hopefully going to spin up this server right here where we can access these different resources so if i control click this now and view it right here this is a simple get request but in a browser and we receive this json data back an array basically of these different objects okay so this is all working now we have json server up and running and we can interact with those resources from our components now the first thing i want to do is retrieve all of this data right here from our notes components and this is where i want to list them so we can see them on this page so the way we're going to do this is by using the use effect hook in this components now if you don't know what to use effect hook is or if you want to learn more about it definitely check out my full react playlist there's videos about use effect in that so the link to that is going to be down below but basically in a nutshell use effect is going to run a function for us when this component first loads and inside that function we can then use a fetch request to grab the data using the end point that json server provides us with all right so i'm going to say use effect like so i'm going to click on the second one to auto import it at the top so inside here we pass a function this is the function that's going to run when we first load this component if you like in the browser now as a second argument i'm going to pass in an empty array and what that does is basically say look only run it once don't run it again every time the component renders because i only want to get this data once okay so inside here i'm going to use the fetch api and the end point we want is this thing right here so let me copy that dude and close this off and i want to paste in right here so this is the end point to grab those notes now this is asynchronous this request it takes some time to do and it returns towards a promise so in that case we can tack on a then method which fires a function when it's done and this function gets access to this response object this is what comes back from this fetch now this response object doesn't contain the data directly and what we need to do is pass it into some kind of form that we can work with and to do that we say response dot json that is a function and what that does is take the json and passes it into a javascript object or a javascript array in our case because it's an array of objects that we're getting back now this is asynchronous in itself and we return it right here so therefore we can tack on another then method which is going to fire a function when this is complete and this time inside this function we get access to the actual data that this gives us and that data in our case is going to be an array of objects these objects right here okay so with this data what do we want to do well we want to store that data in some kind of state so i'm going to say const notes and then set notes and set that equal to use state i'm going to click on this to import it right here the initial value is going to be an empty array but once we have this data right here we're going to update that by saying set notes and passing in the data and that data is just the array of objects that we need okay so now we have that data we want to output it to the browser so we need to cycle through it now the way we do that in react is by using the map method so curly braces because we're using dynamic code then we'll take the notes and we're going to map through those so this file is a function for each item inside our notes and for each item we get access to that individual notes and all we want to do is return some template so inside parentheses for the template and then i'm just going to output a paragraph tag for each one now each one needs a key this is a react thing and it needs to be unique for that particular note so we can grab the id property from that note so let me say note dot id to do this and then inside the paragraph tag i'm going to output the note.title remember all of these are properties on these objects the title so i could output the details as well if i want or the category the id cool so hopefully this all works if i save this and come over to the browser and go to just forward slash the homepage and now we can see all of these notes we just get the title for each one so now we're fetching the data using this endpoint provided to us by json server we're getting that data back and updating the local state with that data then we're cycling through that data and we're outputting a paragraph tag for each one and just displaying the title for each one as well later on we're going to display more details for each one but for now i just wanted to get up and running with json server and grabbing the data cool so this part of everything is done there's one more thing i want to do and that is to send a post request to add data to this file every time someone submits the form and we're going to do that right here so instead of logging this to the console instead i'm going to make a fetch request and it's going to be to the same end points when we're making a post request it still goes to forward slash notes only this time we add in a second argument which is an object and this object is going to have several properties inside it now the first one we need is to say that the method is post this tells fetch that we're making a post request to add data the second one is going to be the headers property and this is to say basically what type of content is going to be sent now the content type in our case is going to be json so i'm just going to paste this in it's an object the property is content hyphen type the value is application forward slash json thirdly we have the body which is where we send the actual json data now what we want to send is basically an object which includes the title the details and also the category so i need to first of all stringify this into json because we can't just send a javascript object when we're transferring data using fetch it needs to be in json format so we say json using the built-in json object dot stringify to do this and then we pass in the object that we want to stringify now the object is going to contain the title the details and also the category so it grabs all of those values category title and details adds them to this object stringifies that and then we're going to send it in the post request and then when json server does this it's going to add this new value to the notes array and it automatically adds a unique id for us we don't have to worry about that property it's going to do that without us having to do anything which is pretty cool so next time we add one it will add an idea 4 or the next id available so this is also asynchronous and once a user has submitted the form i ideally want to redirect them back to the notes component which is just forward slash so what we're going to do is tack on a then method to fire a function after this fetch is completed so this function inside it is going to redirect the user now how do we redirect a user well we can use the use history hook built in to react so up at the top let me do this below classes i'm going to say const history is equal to use history like so click this to auto import it has it done it yep from react router dom and then down here we need to invoke that so we can just say now we want to take that history object and make sure you spell this correctly history dot push which is a method to push on a new route and it's just going to be to forward slash so that redirects them to the home page all right so let's give this a whirl i'm going to go to forward slash create and i'm going to add in a new note so i'll say mario's birthday present and load the details we'll just do a lot of rubbish like this this is going to be a reminder and then i'm going to submit this so now we go back to the home page and we can see that new data right here because remember when this notes component first comes onto the page this function files right here to fetch that data and since we just added that data it's going to include the new one we just added awesome so i know that was all a bit long-winded but now we have json server up and running we don't have to keep revisiting it we have the data we need and we can just now concentrate on material ui again now the next thing i want to show you in the next video is how to display these things in a grid so we're going to have a look at the grid system in material ui

Original Description

🐱‍💻 🐱‍💻 Course Files: + https://github.com/iamshaunjp/material-ui-tut 🐱‍👤🐱‍👤 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 3 & Firebase - https://www.thenetninja.co.uk/udemy/vue-and-firebase + D3.js & Firebase - https://www.thenetninja.co.uk/udemy/d3-and-firebase 🐱‍💻 🐱‍💻 Useful playlists: + Full React tutorial - https://www.youtube.com/watch?v=j942wKiXFu8&list=PL4cUxeGkcC9gZD-Tvwfod2gaISzfRiP9d + JSON Server Tutorial - https://www.youtube.com/watch?v=mAqYJF-yxO8&list=PL4cUxeGkcC9i2v2ZqJgydXIcRq_ZizIdD 🐱‍💻 🐱‍💻 Other links: + Material UI docs - https://material-ui.com/getting-started/installation/ + 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 Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
2 Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
3 Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
4 GraphQL Tutorial #1 - Introduction to GraphQL
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
5 GraphQL Tutorial #2 - A Birdseye View of GraphQL
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
6 GraphQL Tutorial #3 - Project (stack) Overview
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
7 GraphQL Tutorial #4 - Making Queries (front-end preview)
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
8 GraphQL Tutorial #5 - Express App Setup
GraphQL Tutorial #5 - Express App Setup
Net Ninja
9 GraphQL Tutorial #6 - Setting up GraphQL
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
10 GraphQL Tutorial #7 - GraphQL Schema
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
11 GraphQL Tutorial #8 - Root Query
GraphQL Tutorial #8 - Root Query
Net Ninja
12 GraphQL Tutorial #9 - The Resolve Function
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
13 GraphQL Tutorial #10 - Testing Queries in Graphiql
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
14 GraphQL Tutorial #11 - GraphQL ID Type
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
15 GraphQL Tutorial #12 - Author Type
GraphQL Tutorial #12 - Author Type
Net Ninja
16 GraphQL Tutorial #13 - Type Relations
GraphQL Tutorial #13 - Type Relations
Net Ninja
17 GraphQL Tutorial #14 - GraphQL Lists
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
18 GraphQL Tutorial #15 - More on Root Queries
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
19 GraphQL Tutorial #16 - Connecting to mLab
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
20 GraphQL Tutorial #17 - Mongoose Models
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
21 GraphQL Tutorial #18 - Mutations
GraphQL Tutorial #18 - Mutations
Net Ninja
22 GraphQL Tutorial #19 - More on Mutations
GraphQL Tutorial #19 - More on Mutations
Net Ninja
23 GraphQL Tutorial #20 - Updating the Resolve Functions
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
24 GraphQL Tutorial #21 - GraphQL NonNull
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
25 GraphQL Tutorial #22 - Adding a Front-end
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
26 GraphQL Tutorial #23 - Create React App
GraphQL Tutorial #23 - Create React App
Net Ninja
27 GraphQL Tutorial #24 - Book List Component
GraphQL Tutorial #24 - Book List Component
Net Ninja
28 GraphQL Tutorial #25 - Apollo Client Setup
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
29 GraphQL Tutorial #26 - Making Queries from React
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
30 GraphQL Tutorial #27 - Rendering Data in a Component
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
31 GraphQL Tutorial #28 - Add Book Component
GraphQL Tutorial #28 - Add Book Component
Net Ninja
32 GraphQL Tutorial #29 - External Query File
GraphQL Tutorial #29 - External Query File
Net Ninja
33 GraphQL Tutorial #30 - Updating Component State
GraphQL Tutorial #30 - Updating Component State
Net Ninja
34 GraphQL Tutorial #31 - Composing Queries
GraphQL Tutorial #31 - Composing Queries
Net Ninja
35 GraphQL Tutorial #32 - query variables
GraphQL Tutorial #32 - query variables
Net Ninja
36 GraphQL Tutorial #33 - Re-fetching Queries
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
37 GraphQL Tutorial #34 - Book Details Component
GraphQL Tutorial #34 - Book Details Component
Net Ninja
38 GraphQL Tutorial #36 - Styling the App
GraphQL Tutorial #36 - Styling the App
Net Ninja
39 GraphQL Tutorial #35 - Making a Single Query
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
40 Build Apps with Vue & Firebase - Udemy Course
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
41 Updated Vue & Firebase Course (Udemy)
Updated Vue & Firebase Course (Udemy)
Net Ninja
42 Vue & Firebase Real-time Chat (Preview) #1 - Intro
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
43 Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
44 Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
45 Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
46 Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
47 Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
48 Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
49 Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
50 Object Oriented JavaScript Tutorial #1 - Introduction
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
51 Object Oriented JavaScript Tutorial #2 - Object Literals
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
52 Object Oriented JavaScript Tutorial #3 - Updating Properties
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
53 Object Oriented JavaScript Tutorial #4 - Classes
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
54 Object Oriented JavaScript Tutorial #5  - Class Constructors
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
55 Object Oriented JavaScript Tutorial #6 - Class Methods
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
56 Object Oriented JavaScript Tutorial #7 - Method Chaining
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
57 Object Oriented JavaScript Tutorial #8 - Class Inheritance
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
58 Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
59 Object Oriented JavaScript Tutorial #10 - Prototype
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
60 Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja

Related Reads

📰
The Enter key that submits your form while a Japanese user is still typing
Learn how to prevent the Enter key from submitting a form while a Japanese user is still typing, and why it matters for user experience
Dev.to · greymoth
📰
The two-Reacts bug: when packages aren't singletons
Learn to fix the two-Reacts bug by understanding how to handle non-singleton packages in React applications
Dev.to · r9v
📰
🚀 Introducing Prism Guard — An Open Source Frontend Architecture Intelligence Platform
Learn about Prism Guard, an open-source frontend architecture intelligence platform, and how it can help improve codebase quality
Dev.to · Ritumoni Sarma
📰
The Death of the Heavy Hydration Layer
Learn why plain HTML is the new developer flex and how to simplify web development by ditching heavy hydration layers
Dev.to · Amodit Jha
Up next
The masks we wear | Zora Krstić | TEDxLuxembourgCity
TEDx Talks
Watch →