Full Stack MERN Project - Build and Deploy an App | React + Redux, Node, Express, MongoDB [Part 1/2]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

is it free or do we have to pay for the exam ?

👍︎︎ 2 👤︎︎ u/ddhan288 📅︎︎ Nov 02 2020 🗫︎ replies

Im on data rn and dont want to click the video can someone please tell me what does mern stand for?

👍︎︎ 1 👤︎︎ u/seruZ12 📅︎︎ Nov 01 2020 🗫︎ replies
Captions
hello everyone and welcome to another javascript mastery video this one is quite special i prepared for you a full stack marin application from start to finish i initially planned on putting it as a paid course but i later decided to release it completely free for you guys here on youtube so to support this video leave a like comment and subscribe it shouldn't take more than a few seconds now let me give you a quick demo the app is called memories and it is a simple social media app that allows users to post interesting events that happened in their lives let's add a new post to test it out let's say that the creator is javascript mastery title is learning the mern stack description starting with the project and we also added some tags and an image now we can click submit if we scroll down as you can see a new post was just added to the database now we can edit it by pressing the three dots on the top right as you can see our form got populated we can also edit some different ones there we have it and we can also like post for example i can leave a like here or we can delete the post so let's try to do that with this one there we have it this video is a part one of a two part series second and final video is coming in exactly seven days to make sure to be notified when the video comes out make sure to subscribe and turn on the notifications this app might seem simple but it is a full-fledged crowd application that means that if you learn how to build this you'll be able to build most complicated marine applications out there if you think about it every app is a crud app in some way crud stands for create read update and delete you can find this pattern everywhere building a blog create posts read them and delete them building a social media network with users create users update user profiles and delete users building a movie app add your favorites rate them and delete them you get the point if you learn the concepts and the file structure of the project built in this video you'll be able to build more complex projects by yourself without any further ado let's dive into the code [Music] let's start building it first we're going to open an empty visual studio code window you can use any code editor but i prefer visual studio code for many benefits that it has secondly we are going to go to your desktop and then create a new folder you can name it memories project now you have to drag and drop it to your visual studio code once we're in you can go above and then click view and terminal this is going to open your terminal and since we'll be working technically with two different applications here we're going to split our terminal into two parts first one is going to be for our client side application or react side and the second one is going to be for node we are going to create two separate folders as well first one is going to be named client and the second one is going to be called server now we can cd into client with our first terminal on the left side and there we are going to initialize an empty react application by typing mpx create react app dot slash make sure you're in the client directory in terms of prerequisites the only thing you're going to need is going to be the newest version of node just click the newest one and download it for your own operating system while the client side is installing we can create a new file called index.js inside of the server directory this is going to be the starting point of our server application inside of the second terminal we're going to navigate to that server directory and there we're going to run the command mpm init minus y this is going to initialize an empty package.json and now we'll be able to install all the necessary dependencies dependencies that we need are going to be as follows npm install and we need body parser this one is going to enable us to send post requests then we need course which is going to enable cross origin requests then we need express of course we're gonna use express as a framework for creating the routing of our application and then finally mongoose we're gonna use mongoose to create models for our posts and then finally we need nodemon we're gonna use nodemon so that we don't have to manually reset the server every time we make a change instead nodemon will be doing that for us you can click enter and this should install all of the necessary dependencies while that is installing we can go into index.js and import these dependencies first of all we have import express from express then we have import body parser from body minus parser import mongoose from mongoose and finally import course from course just like that now you might be confused if you worked it back in so far you know that the usual syntax looks like this const express is equal to require express thankfully in newest versions of node we can use the import syntax which is a lot more modern and a lot easier to use the only thing we have to do to enable it is that we have to go into package.json and there we need to add one line below the main index.js in here we have to say type make sure everything is in double quota strings so type is equal to module and then add a comma that's it while we are here we are also going to delete this test script and add a start script so start is equal to nodemon index.js now you can close your package.json index.js and wait until our client side is initialized then we'll be able to install all the necessary dependencies for the client side as well react application is initialized let's take a look at what dependencies are we going to need you can go ahead and type npm install and we're going to need axios we're going to use axios for making api requests secondly we need moment moment gs is a library for working with time and date then we're going to need react minus file minus base 64. we'll use this to convert our images and finally we need redux and redux thunk redux tank is used for asynchronous actions using redux with this one command we're going to install all the necessary dependencies while that is installing we can go ahead and check what we have in our client folder inside of here we have an src folder with a lot of things inside of it we are not going to use all of these things so i usually like to just delete the whole src folder and create a new one after you do that there's only one thing that we absolutely must have in our react application and that is the index.js file so you can go ahead and create that index.js this is the file where we're going to connect our react application to index.html file so import react from react import react dom from react minus dom and then also import app from dot slash app we don't yet have this component but we're going to add it soon and then we have react dom dot render the first thing is the app component and then the second thing is document dot get element by id and then we have to specify the string of root with this line we're connecting to the div with an id of root great now we have to create that app.js file app.js and there we're going to have a simple functional component so import react from react const app is equal to a functional component and there we're going to have a return for now let's just create a div and inside of that div we're going to have an h1 which is going to say app and of course we have to do export default app with this we should be ready to run our client side let's save it and let's save the index as well to run the application we just simply have to say npm start that's it great we can see our app here and if we go back you can see compiled successfully for now we are going to close this terminal by typing control c we did that for a reason that first we are going to set up our back end we have more stuff that we need to set up there we need to connect to the database create a mongodb cluster set up the models and also create some documents so first of all we're going to close our client all together and collapse this and then finally just go into the index.js of server that's where we're going to spend the first part of this video in inside of here what you need to do with every express application is first initialize this app so app is going to be equal to express and then you simply run it as a function now we can use all different methods on that app instance first let's do some general setup we're going to say app.use and then inside of there we're going to say body parser dot json and now in here we have to do a limit is equal to 30 megabytes i just did that because we're going to be sending some images which can be large in size and then we're going to say extended is equal to true just like that now you can copy that line paste it below and we are also going to do body parser dot url encoded and put the same thing as parameters we are just setting up the body parser so that we can properly send our requests now we are also going to use that course so we are going to say app.use and just put course in there and call it as a function that's it now is the time to connect our server application with a real database for that we're going to use mongodb more specifically their cloud atlas version of mongodb which means that they are going to host our database on their cloud we can go there the website is mongodb.com cloud atlas the link is going to be in the description and then in here you can click start free and then just create a free account which is going to enable you to create something known as a cluster that's going to act as our online cloud database once you do that you'll be greeted with a website that looks like this you can just go ahead and click build a cluster then you can choose share clusters which is going to be completely free and then you can just click create cluster at the bottom of the page that's going to start the deployment of our cluster it can take one to three minutes but while that is deploying let's do some setup you can go in here to database access and then you can click add a new database user in here you can create your own username and password i'm going to use javascript mastery and then password cannot be simply one two three one two three so i'm gonna use javascript mastery and then one two three just like this now i can click add user with this credentials we'll be able to read and write to any database great finally we need to go to network access and then in here you can click add ip address once you do that you can click add current ip address and click confirm that's it now we go back to clusters and wait until our cluster is deployed now you can click the connect button right here that's going to ask us if we want to connect it with a shell our own application or mongodb compass which is a graphical user interface for looking at our databases data we can click connect your application because we want to connect it to our server side express and node application you can copy this string and then we're going to go back to visual studio code inside of here i'm going to create a new variable which is going to be called connection url all uppercase and then in here you can create a string and simply paste the whole thing that we received right there from our mongodb atlas in here you can enter your username and password make sure to delete these arrows as well so mine was javascript mastery and then the password was javascript mastery one two three you can enter your own credentials that's it of course in real applications your credentials should be secured so we cannot simply put them in here later on in our video before the deployment of the whole application we're going to create environmental variables and then we're going to store that connection url right there the second thing we need is going to be port so const port is equal to process that env that port for now we're going to use the 5000 but later on once we push this to heroku heroku is automatically going to populate environmental variable called port finally we use our mongoose to connect to our database mongoose.connect it is a function that accepts two different parameters first one is going to be the connection url and the second one is an object with all the options we're gonna use two different options first one is going to be use new url parser which we're going to set up to true and the second one is going to be use unified topology which we're also going to set up to true these are not required but if you don't set them up we're gonna get some errors in the console or rather warnings so let's just have it for simplicity purposes now we're not gonna end this sentence right there we're gonna chain a dot then because this returns a promise so in here we're going to have a dot then and also we're going to have a that catch just below now what do we want to do if our connection is successful well then we want to call our app and then on it we want to do app.listen listenex has two parameters the first one is the port which we just created right there and the second one is a callback function which is going to be ran once our application successfully listens that's going to be a simple console log which is going to be template string and it's going to say server running on port and now we can use template strings to say port this needs to be all capitalized that's going to say server running on port 5000 great and finally if the connection to the database is not successful we're going to have an error there and we are simply going to console.log error.message that's it and the final piece of setup is going to be mongoose.set and there we're going to set use find and modify to false so just pass a second parameter false this again makes sure that we don't get any warnings in the console that's it now if we go back to our package.json we specify the script start and let's run it you can go ahead and type mpmstart that's going to run nodemon index.js and we should get a console.log saying server running on port 5000 that's it our server is successfully connected to the database now that we are connected to the database we can start creating routes for our backend application to do that we are going to create a new folder inside of the server which is going to be called routes inside of the routes we are going to create a file called posts.js inside of there we are going to add all the routes that have to do something with posts both being that cars that you saw previously to do that we have to import express from express and we also have to set up our router constructor is equal to express dot router with a capital r now we can start adding our routes our first route is going to be router.get the path is just going to be slash and then in here we can specify a callback function that is going to be executed once someone visits localhost 5000 slash great in here we are always going to have request and response it's going to be the same thing for every single callback function inside of our router.get the second parameter is going to be a callback function that is going to be executed once user visits this route instead of every callback function we have request and a response for now let's just do response.send and then in there let's say this works that's it now we have to export the whole router so we're going to do export default router just like that and now we can go ahead in index.js and import that router which we just exported from there to do that we have to do import post routes from dot slash routes slash posts.js now we can use express middleware to connect this to our application to do that we have to type app.use and then for the first parameter set up the starting pad for all the routes inside of the post.js and that thing is going to be posts and in here we set the routes so what this did is it said that every route inside of the post routes is going to start with posts that means that this route inside of posts is not reached by going to localhost 5000 and then slash it's reached by going to localhost 5000 and then slash posts because we added a prefix of posts to all routes in here now let's see if we can get this response inside of the browser to do that we have to go to this url localhost 5000 slash posts i'm going to copy it go back and then check it in the browser as you can see at the top left corner we get this works which means that we successfully connected our express application and we are running it on localhost 5000 great before we move any further with the functionality we are going to set up an amazing folder structure for all the backend applications that's going to make them much more scalable to do that we are going to create a new folder called controllers inside of the controllers folder we are also going to create a file called posts.js inside of there we are going to create all the handlers for our routes what does that mean well let me put it side by side inside of here we don't want to have some logic because if we keep adding routes and adding more complex logic like this our file for routes is going to get long and we're going to get lost between all the logic and all the requests and at the end it's going to be hard to see what routes do you even have access to to simplify that we can do something like this we can extract all the functions or all the logic from the routes and then take it right here in the posts of the controllers inside of here we're going to declare that function for the router.get let's give it a name const getposts is equal to that same callback function which we just copied of course so that we can use it in post.js we have to first export it right there export const get posts great now we can go back into our post.js and then there we can import all different functions for now we have only one that's going to look like this import and now inside of curly braces considering we are doing named and not default export in there we can name that function get posts from dot slash controllers slash posts that's it now the only thing you have to do is simply say router.get and then we execute a function called getposts in here don't forget to add posts.js in react we don't need to do that but in node we absolutely have to at this point i don't think you can see the purpose of having the controllers and routes separate which is completely fine but as we keep adding more routes you're going to see how clean this is going to look like we'll be able to see all the routes just like this and then execute all the functions in the other file great with that said let's create a new model for our post we're going to create a new folder called models and then inside of there we're going to create a file called post message dot js inside of there we're going to utilize the possibilities of mongoose to do that we have to say import mongoose from mongoose now first we have to create a mongoose schema const post schema is equal to mongoose.schema and that's going to be a function which is going to have an object immediately in there that's it well what is a schema with mongodb you can create documents that look absolutely different one can have the title and the message what can only have the message and so on mongoose allows us to give some sort of uniformity to our documents we are going to specify that each post is going to have to have these things so in here each post is going to have a title which is going to be of a type string each post is also going to have a message which is going to be a string it's going to have a creator which is going to be also of type string we're going to have some tags which is going to be an array of strings so that that's why we put an array sign there we're going to have a selected file which is also going to be a string we're going to convert an image into a string using that base64 then it's also going to have a like count this time we're not going to simply say a number we're going to say an object and then inside type is equal to a number because we have to add additional information and that additional information is that by default we want to set it to zero and finally we're going to have a created add property which is going to be an object again of type date and also it's going to have a default value of new date just like this make sure to call it and write it exactly like this now that we have a schema we have to turn it into a model to do that we're going to say const post message is going to be equal to mongoose.model and then in there we'll do post message make sure to do the same thing here exactly like this post message or you can call it anything you'd like and then the second parameter is going to be post schema that's it now we can do export default post message we are exporting a mongoose model from the post message file and then on that model later on we'll be able to run commands such as find create delete and update great now that our model is done we can start adding more routes inside of here i'm gonna copy the line this route is gonna be router.post and once we go to that route we're gonna run the create post function which we are also going to import from the controllers so in here create post now we have to save it and go to the controllers in here we're going to say export const create post it's also going to be an error function which has a request and response and then in there for now let's do rest.send post creation now is the time that we have to start implementing real logic for getting posts and for creating a post to do that we are going to import post message with a capital p from dot slash models and postmessage.js this gives us access to a real model what can we do with that well first of all each callback function is going to have a try and catch block it looks like this try opening and closing curly brace and then the catch with an error inside the code in the catch is gonna happen if we get an error right there and the code in the try is going to happen if everything is successful so in here let's try to retrieve all the posts that we currently have in the database const post messages is equal to post message dot find just like that now this wouldn't be correct because post message that find or finding something inside of a model takes time which means that it is an asynchronous action for that reason we have to add a weight in front of it and therefore we have to make this function asynchronous after that we can console.log our post messages and finally we need to make our function return something so if everything works then we're gonna say res does status of 200 which means everything went okay and then we're gonna return json which is going to simply be an array of all messages that we have we don't even have to cons log it we're just returning it that's it we also have to respond with something if there's an error so we're going to say rest that status and then in here let's do 404 and then dot json and we're going to return message to be equal to error dot message just like that now this is it for our get posts and how can we see if it works well our server is already running on localhost 5000 so let's go check it out and that's it you can see that we have an empty array this is not that interesting right we just have an empty array now we have to implement the logic for adding different posts and we're going to do that right here to create a post we're also going to do a try and catch block with post requests you have access to something known as a request.body so we're going to say body is equal to wreck that body and we won't be able to cancel like this right now for the reason that we don't have a way to send post requests yet that's the exact reason why immediately after we create this create post we're going to move on to the front-end side to create a form and basic layout for making different posts our request that body is actually going to be our post so we can name it like so and then we need to create a new post we do that by typing const new post is equal to new post message we call it and then in there we pass that values that we're receiving to the request that body yet we are not sending them but we're going to do that once we implement the logic on the front end then in the try block we're going to say new post dot save this is again an asynchronous action which means that we have to add a weight in front of it and also async on the whole function once that is saved we're going to respond with resda status 201 which means successful creation and then that json we're just going to send that new post in that's it if it's not successful we do res dot status and then 409 that's json and then in there we do message is equal to error dot message you can learn more about this http codes right there under the following link it's going to be in the description but generally it looks like this all requests that start with 200 are successful 300 are redirections 400 are client errors and 500 are server errors you can take a look for example you can read only those with stars these are the most important ones and then see what each one says in here 200 is the most popular one the request has succeeded great the link is going to be in the description now we have our create post function completely done and now is the time that we focus more on client and implement the logic for actually sending or creating posts moving to the client side we are now going to create a whole skeleton for the front-end application there is one thing that i forgot to tell you to install at the beginning and that is npm install add material minus ui and then forward slash core this is going to be the ui kit we'll be using material ui is really popular when working with react because it allows you to create nice looking applications without a lot of styling while that is installing let's create our components folder inside of there we're going to have two folders one is going to be called posts and the other one is going to be called form inside of the form we're going to create a form.js file which is going to be our form component inside of the posts we're going to create posts dot js file which is going to be the component for the posts each one of these is also going to have its own styles.js we'll be using materials ui way of styling yeah it's css in js but it's it's not that awful you're going to see it soon and then again styles dot js in the posts that's what we have folders the last thing we have to do is create one more folder which is going to be inside of the posts folder and that name is going to be post inside of there we are also going to create just one thing which is going to be post.js file and also styles.js this is the folder structure that works really well in medium to large level applications you can see everything is nicely put inside of the folders we have the styles there and if only one component uses some other component like only posts uses post then that post component is going to be inside of there maybe doesn't make a lot of sense right now because we just add a lot of files but not a lot of code but it's going to make more sense once we actually start writing code great now that we have the structure of our application let's actually start with app.js first of all i'm going to run the application again by typing npm start and now we can use material ui components so first of all at the top i'm going to import all the components we're going to use in this app.js file all components start with a capital letter and these are going to be container app bar typography grow and grid and we are going to import them from add material ui and then forward slash core great inside of here let's start with basic structure i'm going to delete this div and create a container that's going to make sure to just center everything inside of there i'm going to put the property called max with equal to lg which is large and then inside of there first thing that we have is going to be the app bar app bar is going to have a position of static and also a color of inherit inside of the app bar we are going to have a typography typography material ui basically stands for any textual element like h2 paragraphs or really anything but it gives it a nice looking font so in there we can see variant is going to be equal to h2 and we are also going to have a line equal to center in there we can put the title of our application in our case that's gonna be memories and this is supposed to be variant just like that and then we're going to have our image so image in there we're going to have an src which is going to say memories alt can be memories and then we can put the height to be equal to 60. we don't need it to be more than 60. now we don't have this image yet so let's create it i'm going to leave the link to the image down below and then what we can do is you can create a new folder in the src called images and then inside of there you can download and put that image memories.png looks like this just to give some life to our application i misspelled container there as well now we can import that image that's going to be import memories from dot slash images slash memories dot png great now if you save this let's see if it works okay and we have a huge image right there once we add some styles this should look much better before adding the styles let's just finish with the structure below this app bar we're going to have a grow component grow just provides some simple animation grow is going to have a property of n so it's going to grow in and then inside of that grow we're also going to have one more container inside of that container we're going to have a grid component that grid is going to be of a type container it's going to say justify to space between and also align items to stretch and we are also going to give it some spacing which is going to be equal to three that's it now inside of that grid which is of type container we can add two different grid items let's do that grid and then item excess is going to be 12 which means that it's going to take the full width on extra small devices and on small and medium it's gonna be seven which means that it's going to take seven out of twelve spaces on small or larger devices great so this is our grid component and then i'm going to copy it and paste it below this one is also going to be extra small 12 but we're going to change the small to be 4. inside of this first grid we're going to have our posts component we created a file for it but we didn't yet create or import the component and then just below in here we're going to have our form component now we have to create those components and then import them right there so let's do that let's go into the form and then inside of here we're going to import react from react const form is equal to a normal functional component which is going to return just an h1 that says form for now and then we're going to export default form that's it i'm going to copy all of this now go into the posts file paste it there and then just change the form to say posts and then change this to posts and finally we're going to do the same thing for the singular post component in here i'm going to change posts to simply say post that's it we know our hierarchy our posts is going to use the post component so what we're going to do is we're going to import that post into our posts so right there below the title we need to add a react fragment so we can add multiple things in there below posts we're going to import the post component so import post from dot slash post slash post and now we can create multiple post components just like so let's add two for now great the last thing we have to do is collapse this go into the app and then finally import the components we just exported that's gonna be import posts from dot slash components slash posts and we need to go one level further to slash posts and finally you can copy the line and then change this to form that's it now we are importing the posts and the form as well in here and now we shouldn't get any warnings or errors that we don't have these components here because they are there you can see the app is compiled and running on localhost 3000. let's visit in the browser and see what we have let's be honest this looks pretty bad for now but we're going to keep adding more styles and structure to it firstly let's add styles to our app.js here is how we can properly add styles to a material ui application inside of the src folder we are also going to create a styles.js file in here we need to import make styles from add material ui core and then slash styles make sure to import it not as a default import but as a named import instead of curly braces and then below we do export default we call that make styles and now inside of there we put a callback function which immediately returns an object this video is about creating a mirn stack application connecting it to the database connecting the server to the front end and everything else that we still have to do for that reason you're not going to have to type the styles i'm going to leave all the files for the styles down in the description and you'll be able to copy them so let's start with this one you're going to have these styles make sure to copy these from the description save it and then go back to the app.js in here we have to say import use styles from dot slash styles and the last thing we have to do is say const classes is equal to use styles and call it just like so so this is going to be the process for all different components again we're just going to copy and paste it and you don't have to worry about styles the only thing you have to do is actually add them in here so let's start with the app bar first in here let's do class name is equal to classes that app bar so the same we called it right here great then we have to add the classes for the image so class name is equal to classes that image and then finally class name is equal to classes dot heading right here and i just noticed that i have a typo here this should be height spelled like so great now if we go back to our application let's see how it looks like as you can see this is much better now let's add the styles for all the other components meaning posts post and the form you can do that by going into these styles styles.js and then just copying the link in the description you should be able to find all the styles right there there we go i copy and pasted all the styles for the form and now going into the post.js i'm gonna copy and paste all the styles for the post js as well right here that's it and finally styles for the posts plural this time we don't have a lot that's it after you copy and pasted all these styles the last thing that you have to do is copy the same two lines that's this thing here we have to copy the import use styles and we also have to copy cons classes is equal to use styles so you can hold alt or option and then copy this line and then keep copying this line then you can press ctrl c or command c to copy both lines and let's add the same thing to all these files that's going to be import that and then finally drag and drop it here same thing goes for the post inside of here you paste it import goes at the top and then we have cons classes so that we'll be able to use the classes and the last thing is in the posts in here we also have to import the used styles and then finally use that classes great with this all the classes are now imported and then we'll keep adding the jsx and the only thing you have to do is say to something for example classname is equal to classes.something that's it we simplified your process there because this video is long enough even without adding the styles we have to focus on things that really matter connecting this to the back end and connecting it to the database now let's start implementing the calls to the api we're going to close this collapse it go to client and then in the client we're going to create a new folder called api inside of the api we're going to have an index.js file and inside of there we're going to import axios from axios we're going to use it to make api calls in here we have to specify our url and that url is going to be a string that's going to say http and then localhost 5000 slash posts as we discussed on the back inside so this is the url pointing to our backend route and now in here we can create a function called fetch posts which is going to be equal to an arrow function that's simply going to make an axios dot get call to our url as you remember localhost 5000 slash posts simply returns all the posts that we currently have in the database now we're not going to use it in this file but rather we're going to export that function now we have to focus on adding redux capabilities because all actions towards our backend are going to be done using redux we need to dispatch those actions to do that we have to add some boilerplate code meaning we do have to create a few files and folders but later on on bigger applications this is going to be extremely great because of the scalability and i agree to implement redux you have to add a lot of files and folders but it's going to be great in the long run because it makes our application scalable that means that as our application grows we'll be able to use that same old consistency redux offers us without any trouble great so to do that we're first going to create a folder called actions and a folder called reducers inside of actions we're going to create a file called posts.js and we're going to do the same thing for reducers inside of the reducers we are also going to have an index.js file and this also seems like a good starting point now that that is set up we can go to our index.js file and this is the place where we are going to initialize redux what are some of the things that we need well let's start import provider from react redux provider is going to keep track of that store which is that global state and that allows us to access that store from anywhere inside of the app we don't have to be exactly in a parent component or in a child component we can access that state from anywhere then we're going to import create store apply middleware and also compose from redux finally we need to import thunk from redux minus thunk that's it now let's set it up to set redux we first have to create store so that's going to be con store is equal to create store create store takes in two different things first we have the reducers which we didn't define yet as you can see they are red we need to define the reducers and the second thing is going to be compose which is a function and then in there we put apply middleware and then in there we pass thunk as you can see and looks like i misspelled compose at the top great so the only thing we have to do right now is import reducers we are going to import reducers from dot slash reducers that means that we also have to go ahead in the reducers index.js to export them inside of here we're going to use something known as combine reducers from redux and then there we can say export default and call that combine reducers we call it as a function and then put an object inside of it now in here we can use all of the individual reducers that we have in our case we are only going to have posts so for that reason we have to import posts from that slash post so we can go to that file and now let's talk about reducers what are reducers well a reducer is a function so let's do it like that constructor is equal to a function more specifically it is equal to a function that accepts the state and also it accepts the action then based on the action type so if action.type is equal to let's say create then we want to do some logic here more specifically we want to return either action or we want to return the state changed by the action usually you're going to have multiple if statements for a lot of different things and for that reason people prefer to have the switch statement and this is how it works you have the switch statement and then right there as a key you put the action that type as we discussed and now in here we can specify all of our types for example we know that we're going to have a fetch all action for fetching all the posts and let's also do the one for creating so that's going to be create post great in here we are later going to return some logic but since we don't have anything yet let's just return the state and in reducers the state always needs to be equal to something we cannot have it equal to nothing that's why we have to set this initial value our posts are going to be an array and that's why we are specifying this empty array there and also just to simplify things our state is always going to be simply posts because we are in a post reducer so we can rename the state to posts and also as a default return people usually just put return and then posts that's it we're gonna add logic here later on but now we just need to set it up so it works together once we connect the redux to the store great now you can see that this reducer is currently not being used so what we can do is just export default that function we created we don't actually have to use it here we are using it in here in combined reducers we are importing that posts and then setting posts equal to be posts considering both the key and the value are the same we can only keep the first one that's it we can put this in one line and as you can see our index.js off reducer is done now we are successfully exporting the thing that we previously imported in here in the index.js of the src and now we have this variable in the store now that the store variable is successfully created we can wrap our application with a provider component we're going to do it right here provider and then we wrap our application with it we can do it like so we're going to put the app here and then just move the comma right there people usually like to span it across multiple lines just so it looks simpler to understand and this is it the last thing we have to do is specify the store to be equal to the store we just created right there that's it our application is now successfully using redux and we can start using all of its capabilities looks like we forgot to install one thing which is react redux so just copy that close the terminal by control c and then in there you can type npm install and then react redux once that is done it means that our application is successfully connected to redux now we can start making use of it first we have to dispatch our get posts action and we're going to do that into our app.js so let's go in there in pre-hooks era redux was kind of hard you had to go down here and then do some crazy syntax like this and then map state to props it was crazy now with use of hooks we can use redux much more easily what we can do is import a hook from react redux so import use dispatch from react minus redux what this allows us to do is to dispatch an action okay so how does it work first of all we have to define that dispatch so we need to say const this patch is equal to use dispatch that is a hook now that we have access to this dispatch we need to find a way where we are actually going to dispatch the action and the best way to do that is inside of the use effect use effect is initially going to be just the component that mount but later on it's going to become the component will update so to do that we have to specify the use effect it looks like this we call it and then inside of there we put a callback function and as the second parameter we put an empty array there and finally we can use this dispatch to dispatch an action right now we don't have any actions in here so our next goal is to create an action we can do that right here by importing it import get posts from dot slash actions slash posts you can see it's not currently being used so how do we use it well you just specify the function get posts and then you call it this is our successful dispatch that's it and react is telling us please include the dispatch in here in the dependency array so let's do that great now it's time for us to actually export get posts from the actions let's go there inside of here inside of the post we just have a completely empty file now we have to make use of this index.js file in the api we created not that long ago to do that we're going to do import star as api from dot slash api this import star as means that we import everything from the actions as api that means that we'll be able to use this fetch posts like this api dot fetch posts and we do it this way because we're gonna have a lot of calls exported from the api now we have to create actions more specifically action creators action creators are functions that return actions how do they look const get posts is equal to an arrow function and there we can declare an action const action is an object actions must have the type property in this case let's say that we're going to name it fetch all and also they can have some payload and payload is usually the data where we store all of our posts and finally we have to return it return action this is it we successfully created this action creator the problem is we are working with asynchronous data to actually fetch all the posts some time is going to have to pass and for that we have to use redux tank redux tank allows us to in here specify an additional arrow function bear with me the syntax is crazy but you just have to do this async and then one more set of parentheses and then in there as a property we get access to this patch this is it now we created a function that returns another function and now we can use the async await capabilities of course we have to have another arrow right there great and there is one more difference instead of actually returning the action with redux tank what you have to do is you have to dispatch the action that's it so just to recap let's go back action creators are functions that return an action and an action is just an object that has the type and a payload with redux tank since we'll be dealing with asynchronous logic we have to add this async dispatch function in front of it and then instead of returning the action we have to dispatch it to actually make this work let's add a few lines we're going to add that try and catch block and then in the try i'm going to try to fetch all the data from the api we can do it like this const we're immediately going to destructure the data and then is equal to a weight api that fetch posts so what we're doing in here is we are first getting the response from the api and then in the response we always have the data object which we're returning from the backend and then we get the data and basically data represents the posts so what we can do is in here we can remove this action and we can immediately dispatch an action an action is as we said an object which includes the type the type is going to be fetch all and then the payload is going to be data now we are successfully using redux to actually pass or dispatch an action from the data from our backend in here we can simply console.log the error dot message and if you remember we actually imported this action which means that we have to export it so export const get posts that's it as soon as this action gets dispatched and we're doing that from here we immediately go to the post reducer and there we have to handle the logic of fetching all posts considering we are immediately fetching all of our posts in here we are fetching the data from the api and then sending that data through the action.payload we can immediately in the reducer just do this return action dot payload and that action that payload are our actual posts now we've been working a lot with all of this redux data passing but how do we actually retrieve the data from within our components well to do that we are now going to in the component that actually needs the posts and that's going to be post component inside of there we have to somehow fetch the data from that global redux store we can do that with the help of something known as selectors so in there we're going to import use selector from react redux great now that we have that we again initialize it as a hook we're going to say const posts is equal to use selector inside of the use selector we're going to have a callback function as a parameter in that callback function we get access to that whole global redux store or state and then we can immediately return state that posts how do we know that it is called posts well if you go to the reducers index.js you can see in here we have posts that's it now that we're getting these posts what do you say that we just do a simple console log and put them there great now we save this and let's see if any data is showing up open the console refresh and you should be able to see we do get an empty array at first in post 11 but then we get a network error saying access from origin localhost 3000 has been blocked by course policy there is one thing that we need to do in our react applications to make requests to our server work to do that we need to go back into our package.json of the client side and just below this private to true we're going to set a proxy proxy is going to be equal to and now we need to specify our port http localhost and that's going to be 5000 if we now save this whenever you change a package.json file you need to rerun your terminal so i'm going to close it and then run mpm start one more time and let's see if that's going to fix our issue after i spent some time debugging i found that the thing that we added the proxy that was absolutely necessary but that wasn't the fix to our issue the fix was this little bug right there we specified the routes before we specified app.use course so we need to have the course above the actual app that use routes right there if you now save this and then go back you should see if we refresh that we don't get an error anymore and we just have an empty array at first we have this empty array because that's what we set up right there in the reducer but later on once we make a request then we get the new empty array and that's after the data has been fetched the data has been successfully fetched but still it's an empty array that means that the get request works and now is the time to implement the form so that we can make a post request to our database and actually add new posts let's start by adding the jsx to our form first of all we have to import all the components we're going to use that's going to be text field button typography and paper and all of that is coming from add material ui forward slash core now let's create our form inside of here we are going to create a paper paper is like a div that has whitish background in there we're going to add a class name which is going to be equal to classes.paper remember we imported all the classes so that we don't have to create them now inside of there we're going to have a form form is going to have autocomplete set to off then we can add no validate classname is equal to classes.form and then finally we have the on submit which is going to say handle submit just like that a long line but we have everything that we need and that handle submit is going to be the handler function so we can create it right now handle submit is going to be equal to an arrow function and then later on we're going to add what we need inside of there great moving on to what we have inside of the form inside of the form first thing that we're going to have is going to be a typography more specifically we're going to use a variant of h6 and then inside of there we can say creating a memory because all our posts are indeed memories below that are going to have a text field text field is a self-closing tag and then first text field is going to be about who is creating a post so we're going to say name is equal to creator then variant is going to be outlined label is going to be creator with a capital c then what else do we have we're going to make it a full width so full width just like so and then finally we can add a few more properties that's gonna be value and the on change two of the most important things and this is already getting long so let's space this out in multiple lines variant label full width and then finally the last two are going to be the most important ones and that's going to be value and finally the on change okay great so where are we going to store that value and what is the on change going to do well the value is of course going to be stored in the state more specifically in the state called post data and then dot creator that means that the whole data from our post is going to be stored in the pose data object in the state and then each object key is going to be a specific text field so let's create that state using the use state property in here we're going to import the use state hook and then right there we're going to say const post data and then set post data is equal to use state and that's going to be an empty object inside of that empty object we need to specify the properties that the object is going to start with so in here we need to mention everything that it's going to have first of all the creator property which we just specified is at the beginning going to be an empty string title also an empty string at the start message also going to be an empty string tags is going to be also an empty string and finally selected file is also going to be an empty string we're going to convert an image to a base64 string just in a second okay we can put this in one line so it's easier to read and that's it we can remove the last comma great now we have that post data and we are using that right here in the value so how are we going to change the value of that state field using this onchange well that's a bit harder considering in here we have an object that's in the state and we want to update just one of the object's properties to do that we can use this syntax in here as always we have a callback function that has that event as a parameter then we have the set post data which is a setter method for that state and then in here it would be easy if we could just specify an object and then in this case say creator and then creator is equal to e dot target that value right that would be okay that won't be all that complicated but it's not that easy because later on if we add a second text field that means that we would always override everything and simply have the creator we wouldn't have any other fields because you can see we are not specifying them in this object right here to fix that what we actually have to do is first spread the post data so that's dot dot post theta and then we have the creator right there that means that in every text field if we do the same thing but only change the last property that means that all the data is going to persist while changing only the specific property of that specific text field that's it a bit harder but a great lesson to learn whenever i come across a piece of syntax that is a bit lengthier such as this one i copy it and then go to the website called mem.dev in here i can log in and it's going to allow me to train on that same syntax in here i can just click create a card and paste that snippet right there in this case i just want to learn this thing that's the hardest thing that's the thing that we have to spread and then use the creator we can set the text highlighting to javascript and i can say i just learned how to set the state using an object now it allows me to train it's going to keep asking me to do the same thing until i'm 100 sure that i can replicate this always and it's completely engrained in my memory i know that i need to spread it post data and then finally i have to do creator is equal to e dot target data value and that's it i click submit you can see it's correct and now since i know it i can click easy but if you don't know it you can practice on this and it's going to keep repeating so you can practice it every few days until you actually remember it great that's it just wanted to let you know that now we can go ahead and add multiple text fields this one is only for the creator i'm gonna put all of this in one line since we already know what is in there and now i'm gonna just copy and paste it a few more times we're gonna need it once for the creator once for the title then the message and then finally the tags great of course we have to change the labels as well so this is creator this is to be the title in here we have the message and finally the tags and now we have to change the values as well this thing here is going to be a title therefore title is also going to be here in here and in here we have the message and finally in here and in here we have the tags that's it we now have four text fields now let's do the most important thing we're going to create a div that div is going to have a class name of classes dot file input and then inside of there we have to use that package we installed at the start it's called file base so at the top of our file we're gonna import file base from react minus file minus base 64. and now we can use it as a component file base and we have to specify a lot of properties in there so first of all the type is going to be equal to the file multiple is going to be set to false we only need one and then on done function is going to be set to a callback function where in here we do one destructuring we get that base64 thing and then in here we need to return or rather set post data and then we have an object in there we spread the pose data and finally set the selected file to be equal to this base 64 we are receiving from here that's it we can also put this in one line right now that's it we now have all the inputs we are missing only one thing and these are going to be the buttons so first button right there the button is going to have a class name of classes dot button submit it's also going to have a variant of contained color of primary size of large type of submit and then finally it's going to have a full width property and the button itself is going to say submit you can see we have so many props in here so many but usually if you don't have this you would have to have 100 lines of css for that nice looking button with material ui we just pass props and that's it we need one more button to clear the form for that we're going to copy this one simply remove the class name we don't need it here the variant should be contained in both cases not container contained color is going to be secondary here size is going to be small and then in here we're going to have an on click function rather than type submit so on click is going to be equal to clear that's going to be a callback function to clear it and in here we can also say clear great now as we did with the handle submit let's create that clear so that we don't have any errors there we go and save it now if we go back to the browser we should see a nice looking form and we have a nice looking form but it's not perfect these inputs should be stretching and have some margins so let's see what went wrong there in here what we needed to do is have multiple classes here so we need to make it a template string and the first class is going to be classes that root to actually provide that padding and margin and the second one is going to be classes dot form that should fix the issue let's see if it works save it and then go back as you can see now we have those margins and the last thing would be yeah in here we have full width value but we need to separate these words of course so if you do this like this and go back that's it we finally have a nice looking form and now that we make a post request we are going to be able to add a new post into our database connected to our server now let's add the api request and the action for the post request first let's go to the api and then in here we're gonna do export const create post in here we're going to have a callback function this one is going to take in one parameter and that parameter is going to be the entire post after we get the post we can say axios.post first we have to specify the url and then we have to specify the data we are sending of course in this case the data we are sending is going to be the whole new post now that we are exporting this we can go back to actions inside of the actions let's create it export const create post is going to be equal to the same thing an error function which then returns another error function with a dispatch right there that comes from redux tank and finally we're going to do a try catch block inside of there try catch inside of the try we need to get that data so that's going to be const we destructure the data from the response and that is equal to await api dot create post this is basically making an api request a post api request to our backend server and we are sending a post right there finally we're going to dispatch an action the type of the action is going to be create and then the payload is going to again be the data just like so great in here we have the post and the post we're receiving it if you remember through here so in here we're going to say post great and finally if this is not successful we are simply going to console.log the error just like so now if you remember correctly we have to dispatch that action to do that we can go into the form and then in here we can import that use dispatch from react redux import use dispatch from react minus redux just like this great we have to use it right there cons dispatch is equal to use dispatch and now this allows us to actually dispatch actions the question is where do we want to dispatch it well of course on the handle submit once the user submits we want to send over a post request with all the data that user typed in first of all we always have to say event that prevent default not to get the refresh in the browser and then in there we're going to dispatch an action so dispatch this time it's going to be create post and now inside of there we're going to pass all the data from our state post data you can see create post is still red which means we have to import it from actions so in here we can say import create post from dot slash dot slash actions slash posts just like that i can see event is not there so we have to specify it here and now we are making that request once we click the submit button great once the action is dispatched then we go to reducers right there in the post reducer and then what do we want to do once we go to the create well we have to send over an array of course we have an array of posts first of all we have to spread all the posts and then we have to add a new post and that new post is stored in the action.payload that's it now if we save that if we are lucky enough if we don't have any bugs this should actually work let's go back to our form let's try creating our first memory inside of here i'm going to put creator as js mastery the title is going to be new year's eve 2019 the message is gonna be had a lot of fun i guess and then let's add some tags let's say new year and also happy new year people do that with hashtags right great now we have to choose a file okay i prepared a nice looking fireworks there let's save it and now let's click submit and hope for the best as you can see something happened and we got our way back array that has one file in it that seems great of course we are not seeing anything yet because our posts and post is not displaying anything but if we go back to our cluster and then in here you can go back to atlas and then click collections if you go into collections you can see the data that is actually in the database in here we have post messages and would you look at that that definitely looks like the object or the memory we just created which means we right now at this point successfully created a full stack marin application first our react application more specifically the form right there sent a post request to our backend application then the backend application communicated that to our database and that's it we have this file saved that means that now we can set up the posts and the post create some jsx there and that post is going to be there every time we refresh the page and we can keep adding new ones that's it for the part 1 but don't worry part 2 is coming in exactly 7 days you're already half done because next video is the last one next time as you can see we're going to add the post component like edit and delete functionalities and much more to make sure not to miss the next video like and comment on this one and if you haven't already make sure to subscribe and more importantly turn on all notifications by clicking the bell icon you can also help sponsor javascript mastery by clicking the patreon link down in the description stay safe and see you in the next one you
Info
Channel: JavaScript Mastery
Views: 533,099
Rating: 4.9725027 out of 5
Keywords: mern stack, mern stack tutorial, mongodb tutorial, react full stack, full stack, mern stack project, web development, react js, mern stack tutorial 2020, mern tutorial, node.js tutorial, react and node, mern stack crash course, react node express mongodb, mern stack traversy, mern stack full project, mern stack 2020, mern stack tutorial for beginners, mern stack tutorial step by step, mern application, mern app, full stack mern application, mern application example
Id: ngc9gnGgUdA
Channel Id: undefined
Length: 75min 40sec (4540 seconds)
Published: Fri Oct 30 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.