Build A Realtime Chat App In ReactJS and NodeJS | Socket.io Tutorial | MERN Chat App Using ReactJs

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
foreign [Music] [Music] [Music] thank you [Music] all right [Music] hello developers before going to any type of intro I want to share with you the bonus part of this tutorial on your number of requests we have integrated this chat application in the same social media application that we have made previously how amazing this sounds so these are the some users available on our social media platform and you can actually chat them in the Real Time with all the amazing features of online status sending emojis time ago and many more you can expect in a chat application by the way if you have not watched the previous tutorials of social media platform then don't worry we are going to make this application from the scratch but I highly recommend you to watch them also because by following those tutorials you will learn how we have made this amazing design of a platform where you can actually share your images and memories and many more now let's talk about the stack we have used in building this application we have used the socket.io mongodb express and of course the node.js so that's enough for the intro let's get started and move to our vs code but before going to start the real production of this chat application I request you to please subscribe and hit a like for this amazing tutorial I just noticed that many of you people have watched my previous tutorials but not subscribed to the channel so please subscribe the channel and press the Bell icon too so this is the directory from our previous tutorial with a client side and a server side so let's start this tutorial by making the rest API for the chat application inside the server side inside the model I am going to make a model for the chat so just name it as chat model dot JS okay here first of all I am importing Mongoose from Mongoose like this okay now let's make the schema cons chat schema is equal to Mongoose dot schema like this and then inside the schema first of all I will have the members so this will be the type of array okay so let's make the type as array this is just the enough field for making a complete chat schema that a chat schema only takes the record of members inside a chat means the ID of the users okay let's close the model after this I am also making a property true within timestamps as true let this delete extra braces now let's format that okay so this is our total schema it's time to import this and shift cons chat model is equal to mongoose dot model and the name of model that chat and I am sending the chat model okay now let's export it as export default chat model let's make another model for our messages here inside the models I am making a file with a name message model dot Js here again I have to import Mongoose so just copy this and I'm pasting it here after this cons message schema is equal to new mongoose dot schema of course and inside the schema I will have some Fields like the chat ID and it will have a type string and after this I will also have the sender ID so sender ID will also have a type string and our last field will be the text that what is the actual message okay so of course it will be also type of string and similarly at the end I am making its time stamps as true so time stamps and then true let's format the code now let's make text a little bit visible let's make a model from our schema I will say cons message model will be equal to Mongoose dot model with the name message and it will have our message schema okay now let's export this model to use in our API so export I think it should be default okay so yeah now let's save this let's make this ambigger as for a proper convention now we have a model for our chat and for the message let's make the route for our chats okay so I am closing them and inside the server inside the routes here I am making a file with a name chat route.js okay as we know first of all I have to import Express from Express like this and let's make the router from the Express dot router okay now it's time to Define some paths or you can say the routes to interact with our controllers of chat so here I will say router dot post simply on a slash then interact with uh create chat controller by the way to make this process all clear first of all I will export my router from here like this and inside my index of server side here I am importing this route so here I will say import chat route from the routes and then the chat route.js okay so at the end here I will say app dot use and if someone is interacting with the chat route then simply go to our chat route like this okay yeah so now you can clearly have an idea if we have a URL of chat slash and the HTTP method is post method then we will interact our create chat controller okay after this I will say router dot get and user ID then find the user chat okay let's make it capital like this here I am saying if someone tries to get all the chats of a specific user then the HTTP method will be get and in the parameters we will send the user ID and interact with the user chats controller of course we have to Define them but on letter okay and the last route will be the finding a specific chat with a specific person so here I will say first ID and then the second ID at our route will be the find chat let's make the controllers of create chat user and find chat let's save this and inside the controllers okay here are the controllers I am making a new file with the name chatcontroller.js inside this first of all import the chat model that we have made in the first from the models and then from the chat model dot JS okay now our first controller will be the create chat like this it will be an async with the request and response effect Arrow function here let's make a new chat constant okay and this new chat will be according to our new chat model okay I will explain this but for now make the members of this new chat equal to request dot body Dot sender ID and request dot body dot receiver ID so yeah like this okay what is happening here basically here I am making a new chat instance from our chat model and inside the chat model I am giving the members that I will fetch from the body of our request and inside the body of course I have to make a sender ID and a receiver ID so basically I will get an instance of our chat model by doing this so now we have to interact our database so here I will make a try catch block and inside the cache I will simply say response dot status equal to 500 and inside the Json pass the error and inside the try block I will say forms result will be equal to a weight and of course I have to save this new chat instance in our database so I will simply say newchat.save and response dot status of 200 means okay and in the Json I will send the result means that new chat let's make the second controller export cons user chats and again it will be an A String with the request and response as parameters okay to find the chats of a specific user I have to interact with the database therefore I am writing a try catch block okay so let's cover the catch block by just simply copy and pasting this from here so yeah now inside the try block I will say find a chat and this chat will be find it from our chat model chat model dot find and I am giving my query as the members should include okay so what it should include the params user ID means as I have already mentioned you when I have to find the charts of a specific user I will send the user ID in a parameter so by following the same pattern I will say find a specific chart from a model and inside that chat the members should include the ID from the parameter of our request so this is the thing that we want to extract from the database okay if this happens correctly then send the response with the status code of 200 and in the Json I will send the chat that we have founded it is not necessary that we will find only one chat because one member can chat with the many other persons so therefore it will be a type of an array it's time to make our last controller which is the find chat like this and again async request response okay so as I have mentioned earlier while finding a chat we have to give the two IDs in the parameters the first ID the second ID okay so I will use both of these IDs to interact with the database let's make a try catch block and inside the catch block again the response with the status code of 500 and the Json there will be the error okay so inside the try block I will say find a chat from our chat model like this okay and I'll save I think it's giving all the way correct suggestion so let's use this okay there is an extra braces now remove this you know when we are sending the two IDs of first person the second person then then there will be only one chat available in a database related to the two persons okay so I am finding that specific chat and I am saying in the query that the members should include both the first ID and the second ID and it's a quite obvious okay so I think now you understand and still there is a kind of error with this braces let's see why this is happening so basically I have to give the two curly braces because one from the query and other from this find one okay so by the way it's time to import these controllers in our route so I am just simply place the cursor and press the controls plus space and it will give me a suggestion press the enter similarly for the others and yeah boom all the controllers have been imported successfully before testing our API let's double check our all the code for the rest API okay so basically there should be a DOT JS like this to successfully import the these functions from the chat controller and inside the chat controller let's double check create okay this response inside the find chat we just forget to send the response so response dot status with the code of 200 and inside the Json I will send the specific chat that we will found let's save this inside the index.js we have imported the chat route and make a chat okay let's start our servers so here I will go to the server directory and write npm start there is an error inside our chat model let's see what's there is chat model dot JS so here we should not write chat model it's the chat schema I probably assumed that you are not seeing that and I just made an error let's save this again and here our server is starting and it's saying bad authentication let's double check our authentication so inside dot EnV here okay okay basically I just forget that I have changed the password of my mongodb after the last tutorial so I am just changing the password inside this string and I will be right back so I have changed the password now let's restart the server and now hope for the best yeah now it's listening on the 5000 Port here is our Thunder client and that was our previous request for the social media so inside this I am making a new folder with the name chat request or insert and inside the chat request let's make a new request with the name create chat okay so I will send this request towards the localhost and of course 5000 because the port our service 5000 the method is post inside the body I will say the sender ID will be equal to 1 from our database so that is my database inside the users I am just taking this ID of a user Zen and pasting it here like this and after this the second field is the receiver ID so okay the receiver ID is the second so this is our second user and so here as I'm making a new chat so I have to specify the chat route like this now send this request and here is our new chat with these two members as we have sended them from our controller okay let's see here we are sending this result it's time to test our second controller which is the user shares as for now we have only one chat for this user so let's try this if we get the result or not so inside chat request I am making a new request with the name find user chat okay let's say find user chats like this again towards the Local Host 5000 and then inside the chat as we did here similarly for this and if you remember inside the chat crowd we just mentioned that we have to pass the user ID as the parameter so therefore here I am passing the ID and okay just send the request and here we have the response inside the array we have only one object because for now we have only one chat in our database similarly Let's test our other controller which is the find chat okay basically inside the find chat we will just acquire only one chat from all the chats that includes both the users that we will send in the parameter so let's make another request and will say find specific chat with users Okay so so again towards the localhost 5000 I am giving the chat route with the first ID as of the Zen and second ID there should be of okay the Umar so let's paste it here let's confirm again if that are not same okay here is our chat route with the get method first second okay this we should specify the find parameter so after the chat we should write the find and now let's send this here we have the result we have only single object that was our expected Behavior which contains the members and the chat ID so it's working very fine now let's make the controller for our messages so inside the controller I am making the message controller dot JS and of course I have to route for the messages so here I will say message route.js import Express from Express as we did before okay and then make our router from Express dot router like this and then we need only two routes first route to add a new message in our database so I will say router dot post only the slash then I will say add message controller will be enabled and similarly when someone tries to get messages of a specific chat then he will send the chat ID in the parameter and get messages controller will be enabled now export default and of course the router inside the index.js of our server I will include this route okay so here import message and route from the routes and then the message route.js okay now I have to use this route so just copy its name and here I will say app dot use the message and then message it out Okay so yeah like okay there should be a comma like this so we have made a complete path for the routing up about the messages now I have to make these controllers of add message and get messages so inside the message controller first import the message model okay so message model let's see if we have exported the message model because I am not showing the auto suggestion so message model dot JS okay here we are exporting it I don't know why it's not using authorization by the way from models and then message model dot JS okay so it's fine now here are the models and inside this VMS model.js after this let's make first controller of add message for this again async with the request and response fat addo function now I will extract the chat ID first of all so chat ID the sender ID and the text from the body of our request so request dot body okay after this I will make a instance of our message model so I will just simply say cons message will be equal to new message model and inside the model I will send the chat ID and the sender ID and the text okay then just close this completely so here our instance is ready to save in the database because we have detected database let's write try catch block so yeah inside the try catch the American result okay so here I am saving the new message in a database and we will obtain a result and At Last I am sending the result in adjacent with the status code of 200 it's time to make a catch block with simply error and send the response dot status of 500 with the adjacent of error message okay so by the way I am just taking all these Auto intelligence Suggestions by the GitHub co-pilot you can also apply and it will take some time for registering your account on the GitHub pilot so you have to wait but it's an awesome extension as you can see how easy our work by using this okay it's time to make our second controller which is the get messages okay let's double check if we have the same name inside the route okay get messages I am just simply copying this and four const get messages again the async with the request and response now first of all I will take the chat ID from the body of our request okay so okay there will be a curly places like this okay so from the request dot patterns as we are sending the chat ID in the parameters as you see in the route here I am sending in the URL over chat IDs so I am just obtaining from the parameters of our route the chat ID so now I have to interact with the database so simply write a try cash block first of all the result will be obtained as a weight message model dot find where the chat ID exists okay so basically as we remember inside the message model every message has a chat ID okay so inside this controller basically I am finding all the messages and obtaining the array of result okay I am obtaining the array which have the same chat ID as we get from our parameters in the response I will send the status of 200 and similarly in the Json I will send the result now for the catch block I think you know everything like this let's save this and inside the route let's import all these controllers by Auto suggestion and like this now I have to write it here dot JS and inside the controller okay now let's see if our server is crashed or running okay it's running by writing RS you can again restart your Express server okay so listening at 5000 minutes is working fine it's time to test our message route so here I am making a new folder with a name message request okay so inside the message request let's make a new request of add a message okay so our URL will be the localhost 5000 and our route name is message as in the index.js we should always double check so because many times it just cause problems if we don't specify the correct name okay it's the message yeah so let's go to again add a message here inside the body I will make a chat ID okay so basically I am obtaining the chat ID for my mongodb database so let's refresh this database and here I have the chats model so inside the chats we should have only one document okay I am just copying its ID from here and pasting it inside my API request then the sender ID sender ID will be the ID of a user so inside the users I am obtaining this idea of our first user and just paste it here our last field is the text okay so the text will include hello how are you now let's test this by making it method as post and hope for the best okay sync cannot post to the message route there is something missing so I basically think I have not saved the index.js therefore it's not working okay let's wait again and try again to add a message yeah now it's working I just forget to press the Ctrl s on our index.js that was the total error okay so here we obtained a message so if I go to the mongodb and refresh my database so I should have a new model of messages here we have the messages and I have one document which is saying hello how are you means our rest API is working fine let's test our second request of get messages so new request and say get messages here again let's write localhost 5000 and the route is message and here we have to paste the chat ID so I am just taking the first chat ID this one and in the result now I should obtain only one message hello how are you okay so let's try it okay here I have only one object inside the array of objects which is having a message hello how are you with the chat ID sender ID so our total rest API is completed now for the chat application how easily we have made this it's time to implement the front end of our chat application let's start let's close all of these files okay and now I am going to the pages of our client side so here I have the pages inside the pages I am making a new folder with the name chat inside the chat Let's Make A chat.jsx and A chat.css okay so inside the chat.jsx rafce and now I am going to the app.js of our client side here it will enable the route towards the chats so I am making an other route and I will say if the path is chat in this case return the element and if the user exists means if the user authenticated then return the chat component okay yeah means the chat page and if it is not then returns to authentication side so let's save this and I have to run the client side so making an other terminal CD client and let's write learn start let's wait for starting it so here my app is started I am logging in as Zen gmail.com with the password Zen okay so if I here just write the chat okay so it is trading with the chat page so our route is working fine but we want whenever we click this chat PNG then we should route to the chat page so for this let's close the terminal and go to our component which was saying right side dot GSX okay so here I have the PNG of comment means this message PNG and I am going to make it under a link I will say link to the chat like this and our PNG will be inside of this section now let's save and try it if I click here now so you can see that we are navigating to the chat page it's time to implement the body of our chat page let's start so I am closing this our app.js because routing is completed and before making the body inside the chat.css I am pasting some styling okay you will find this style Link in the link where I will post the GitHub repository and you can just simply copy and Page styling I am skipping the styling part because the tutorial will become too much long so I am just focusing on describing you the pattern of socket IO and you should understand the logic soft socket IO how it will integrate with the mongodb and how this all scenario Works The Styling is a very basic thing so we are just keeping this for this tutorial so yeah just close the chat.css and start our chat.jsx I am just removing this div and make my own with the class named dot chat inside this first of all I will have a left side okay because in the pre-bit version if you remember we have all the chat section on the left side so for this I here I'm making a div with the name left side chat okay inside the left side chat I am making a H2 heading which will have the name chats before going on I should also declare the right side first so here I am making right side and making our div with the name right side chat like this one now let's save and import the CSS here so I am saying import from the same directory chat dot CSS let's save and see the results but to be sure if the total styling is applied or not I should inspect the elements okay here I have the left side and all the things are available for the chat I am also having and similarly for the writer let's write something inside the right side first so I just simply write here right side like this now see okay it's working fine let's move on for our left side chats container so So Below the heading here I am making an other div and I will set it as chat list like this and inside the chat list here I will have all of my conversations headers okay means the inbox like items in a proper column alignment and here I just noticed that I have missed one thing that first of all I should have a logo search component first as it is found in our previous tutorial part so I am just simply importing it as logo search from the and Logo search and lotion yeah let's save this and have a look okay here we have our logo search after this this complete conversations and the chats should be inside the chat containers so therefore here I am making a chat container like this and closing this here let's save this okay so here we have a proper alignment of our chat container now I have to import all the chats from my database in the chat list so it's a lot of work to do here first of all I will make a use date okay so here I will say chats and then set chats it will be a you state from that react and at the start it will be just an empty array and after this I will fetch the details of our current user who is logged in from our Redux store for this reason here I will write forms to user will be equal to the use selector from the react readers and from the state okay it will lie inside the auth reducer like this and then the auth data now if I just console unlock the user to find if it is fetched or not from our Redux store I am just consoling log and there is an error let's see what the error okay it is saying cannot read properties of undef undefined auth data okay that was happening just because of this w I know probably you were not seeing it but I was not able to notice it now okay so now if I see my console here I have an object and it has all the information about the current user means working fine okay it's time to fetch the chats from our database means mongodb so for this reason here I am making a use effect and inside the use effect let's make a function and the function is the get chats like this and this is an async function because we have to interact with the database and this is a fat Arrow function now make a try catch block and inside the catch block I am simply saying in case of any error just console log the error now inside the try block I will say cons data is equal to a weight user chats and inside the user chats I will give the user ID so basically we have no requests like the user chats for now so let's make a request that will interact with the database on the back end so inside the request folder inside the client and SRC and here I have the API and I am making the chat request okay dot JS now I am simply just copying this name that I have given here user chats so here inside the chat request import axios from the axios like this and make the function export const and simply paste the name that we have declared before and in the parameter it will simply take the ID of our user that we are sending from chat.jsx as you know user.id so here it is receiving in the parameter ID and it will make a request by the API dot get towards the chat and then in the dollar sign ID so as we are using the variable inside our string therefore I have to use the backticks instead of these signs okay now I don't have any base URL to make the API request so I am simply making const API is equal to xgos dot create a base URL with the HTTP okay towards the localhost five thousand so whenever this user chats runs it will first call the base URL of localhost 5000 then it will make a get HTTP methods towards the chat route with the parameter of the user ID let's save this and import this inside the userchat.jsx so okay now after doing this I am saying set chats is equal to data we retrieved and also console log the data let's hope for the best here is an error this is just because of GitHub copilot so okay now let's save again inside terminal okay so basically nothing is happening because we have never called this catchers function okay so I am saying call the get chats every time when the user that has been logged in is changed so here now let's try again and see the terminal here I have an object and inside the object I have the members I also have a chat ID and I created ad so this means it's working fine it's time to display that specific chat inside this chat list so what I will do and here for the chat list section instead of just simply making it as compensation text here I am going to implement some logic I will say chats dot map and then for each chat make a fat Arrow function and then I am just passing our div okay the div should be like this one and inside this div I am passing a independent component which is the conversation and then giving it some parameters like data is equal to the chat means the specific chat that is passing from the parameter okay let's remove this and the other one is current user which will be equal to the user dot ID that is currently logged in okay and let's close this component format the code okay now I have to make this components so inside the client side I am going to SRC inside components I am making a new folder conversation okay inside the conversation make a file conversation dot GSX here rafce and just simply save this and try to import this via the suggestion like this now save okay there is no difference means app is correctly fine let's make the text bigger okay here I am receiving all the props like data and the current user so so now it's time to make some use States and to use the use effect hook of the react to obtain the desired data to display a conversation header in the right side here I am making a use State user data and set user data and at the start it will be equal to the null okay so for which user I am talking right now this is the user to whom we have to chat or to which header we have to show on the right side means if I am logged in as Zen and I have to chat with the Jawad then Javad is this user so now use the use effect like this and in this use effect I am making a function and in the function I will say cons get user data async and then the fat Arrow like this okay to implement this get user data first of all I have to identify for which user I am talking right now so therefore I will say const user ID is equal to data dot members dot find for each ID okay where the ID is not equal to the okay there should be an explanation mark like this current user ID okay so there should be ID like this because here I am sending this okay so now it will be all clear for us I have to import the U State Hook from react okay similarly for the use effect okay basically here I will have the user ID of the other user because inside the chat members if I just open the chat model for the reference here you can see inside the chat model we have the members array and the array contains the two member the one which is logged in currently and the other one to which we have to chat okay so in this case I have to get out the ID of the user to which we have to chat and inside the members I have the two IDs first one is my on ID and second one is the other person ID so I am checking each ID and I am saying just filter out that ID which is not equal to our current user ID so now I think it's making sense for you okay just simply console log at first to see if it is working or not so let's save this and I should also put a dependency here for our use effect otherwise it will render infinite time and I will say it send just empty array let's save this and here if I open the terminal here I have the ID of the other person it's working fine if I just go to line number here you can see it's our desired line number line number 10 of the conversation.jsx so let's move on now just remove this console log line and implement the get user so inside the function I will say cons data will be equal to a weight get user and I will just simply pass the user ID that we have fetched and then I am saying set user data okay set user data equal to the data so I have this request get users in my user requests okay so if I go to the user request.jsx here if you remember we have the get user request so I am using the same request let's add to import this okay so yeah from the user request and if I double check again okay so yeah now we will have the data also to double check it let's console log it so if I console log it and just call this function get user data in the use effect and open the terminal so here in the last object I have all the data recording to the second user who is which is the umer and all the followers following admin everything is here it's working fine now but here I should take a knot of one thing I am interacting with the back end and I have not put the try catch block so it's important to implement try catch when we have to interact with our backend because in case of any error our app will not be crashed so catch error and it will simply console log the error yeah now let's save this okay so our data has been fetched finally it's time to make the body so here I am just simply deleting this one and making my on with the class name of follower and also I'm giving it an other class name of conversation I am giving this class name just because of the styling purposes I have declared the CSS with these stylings so I am not going in the detail of the class names after this I am making an other days and inside this div here I am making a div for the online dot so what I will say div Dot online Dot and then after this I will have the image of the user so image and inside the image the source of the image should be declared first so I will say user data if exists then check for the profile picture okay if I open the terminal here you can see easily is the object retrieve there should be a field profile picture okay there is no profile picture field because Umar has no profile picture set on his profile let's check by going to the our social media application here okay there will be a user with the Umar Khan okay this is the Umar and he has set no profile picture therefore we were unable to see his profile picture field in the retrieve data okay by the way we will handle this also if first the user data exists then check for the profile picture if it also exists go for the If part okay means if the profile picture exists then take the process dot EnV dot react and we have set the name inside the in EnV file so if I just go to client and EnV here we have the public folder for our server where we were placing all the images in our social media application so that was just like a CDN so I'm copying this name and just paste it here like this and also the user data Dot profile picture okay so what this basically total line of code is saying first of all I should open the word wrap okay so now I am seeing if the user data exists then check for if the profile picture exists then make the CDN available for the source and change the string by adding the user data dot profile picture string inside our CDN value now if it does not exist then also go to the process.env and the public folder so I am pasting this and make the default profile okay default profile dot PNG let's save this and check here we have the dot and the default profile PNG of course for now it's not working fine because we have not given all the class names and all the other things but let's just complete this okay our image also have a class name of follower image like this and just declare its styling as let's fetch the name of our user So Below this image I am making are due with the class name of name and I am also giving it some styling so for the styling I am just giving it the font size okay that should be large like this the font size of 0.8 REM now there will be two Span in the first pen I will say if the user data exists then check for the first name and close the curly braces and give a space then user data dot last name as we have stored in our database this spans will just simply saying online or offline okay so just for now make it online because for now we have not Implement our socket dot IO the online and offline will be handled by the socket.io let save this and see here we have the conversation headers very beautifully handled after all of these divs I am making an HR so so by making HR out of all these divs there will be an error that our component has no parent GSX so just make an empty node like this and okay now format the code let's save and here we have our HR very beautifully enabled it's time to give it a little bit of styling let's save this and here our divider line is looking very beautiful so basically our conversation component is completed now it's time to implement the chat body or you can simply say the chat box completely on the right side I am closing all these files of user request conversation chat request okay inside the chat.jsx below this right side instead of just simply writing text here I am first of all making a deal okay and for this deal I am giving some styling so basically what I am going to put inside the div if I go to the right side dot GSX here I have some nav icons okay so I am just simply copying this deal and pasting this here okay now I have to import link from the react router Dom here and URL settings so I was importing the UI settings okay basically this thing we have to do by making a separate component of nav icon mean the separate GSX component but for now and to limit it and due to the limited time I am just copying and pasting okay I also have to import these pngs of home and notification so simply copy and paste them right now again I am repeating that you should do that by making a separate yesx component let's format the code and save it and for the styling I am giving it a width of 20 REM like this and align self towards the flex end let's save and see the result here I have the nav icons okay the command PNG was not successfully imported let's see what's the error here so this is the home notification and for the comment okay so that was Lie Here I also have to put this like now so here it's working fine include this nav icon divided matching pair okay below this I have to make the chat body so for the chat body I am going to make a separate component with the name chat box and I am passing some parameters like chat is equal to the current chat and current user is equal to user dot ID okay there is only one error that we don't have the current chat functionality for now so I am going to match and other you state with the name current chat and set current chat for the default it will have the use state of null I am going to set the current chat on clicking a specific conversation so on the parent diff of conversation I will write on click and there will be a function executed current chat equal to the chat that was passed in the chats.map parameter so let's save this and I have to make a chat box component so inside the components I am making a new folder with the name chat box inside this I am making a file chat box dot GSX here rafce let's Simply Save this and import this by artification and see the result here I have the chat box okay inside the chat box first of all I am receiving all the props what that are the chat and the current user like this now instead of making this div I will make an mpgsx node and inside this there will be a div with the chat box container like this so now first of all make some you state that as we have made in our conversation component like that one user data so similarly I am just copying this and pasting this half frame produced it from react and after this I have to make the used effect like this and inside the I am fetching the data for the header and it's good if I make a comment I will say fetching data for header of our chat box so inside this as we have did in for our conversation I just found a user ID of an other person similarly I am doing here and as our prop is only the current user so I'm deleting the ID and instead of data I will say it as the chat they should also be the chain operators okay because this will not be available for always after this I have to make the function get user data as high as I have made here let's copy this simply and paste it here once again I have to import the get user from the user request let's remove the console log from here and Here Also let's save this and I am giving a dependency array of chat and current user means whenever these two props will change this use effect will render and here if chat is not equal to null then execute the get user data function in the use effect if I just simply for now console log that data let's see if it's working or not if I refresh open the terminal there is nothing for now if I click on the Umar Khan and now here I have the data fetched from the database means it's working fine so now let's make the body of our chat box here inside the chat box container as I have fetched the data for the chat header so let's make it again first I will make an empty node like this and now inside this node make our div with the chat header and then inside this I am going to make the div with the class name of follower and inside this div I am just simply copying and pasting all the this div okay so go to the matching pair basically just copy all this data from here okay just copy this inside the chat box here I am pasting this okay now I don't need this online span inside the chat box also I don't need this the online dot let's format the code save and see the result if I just inspect the terminal here here I am also not getting the it up because I have not selected the Umar Khan now there is the data that was just because I have not clicked on this conversation of Umar Khan now everything is clear I have to make an HR after this these three divs as we have did before inside the conversation I am just simply copying this HR and pasting it here now let's save here our header is almost completed now it's time to make the messages so after this I am making the chat box message messages yeah just like this one and for this I am again making our deal with the class name of chat body so to make the chat body I have to fetch the messages from the database that will be rendered inside the chat body so to make this I have to make a use state so I am making a used kit messages and set messages and at the start that will be an empty array now I am making another huge effect and giving the comment as fetching data for messages yeah and use effect inside the use effect make an arrowhead function with the cones fetch messages like this one and this should be an async function and now after this the try catch block of course with the phones data will be extracted from the HTTP request and yeah here I will just simply say that get messages and I will give the chat dot ID but still I have no request as like of get messages but we will make it later on and after getting data I am setting the messages as the retrieve data and inside the catch block there will be an error simply console log T error now I have to make a dependency array and this dependency will simply depends upon the chat we have selected and the messages will only be fetched if the chat is not null okay so our total use effect for fetching message is complete now it's time to make the get messages request so inside the request folder for the client side here in the API I am making a file message request dot GS first of all just copy and paste from of configuration from here I am copying this and pasting it here export font get messages and then the ID that will be carried as parameter and then simply API dot get and I will go to the messages route with the here okay I can simply just put it like this but the more easy convention is to use the tactics and then use a JavaScript variable or constant you can say so here make a dollar sign and write the ID okay let's double check our route by going to the index.js on the server side okay this is only message so basically I am going to the wrong path here should be the only message now save this and I am importing this inside the chat box now let's save it again and I should console log it first so control log data now let's save it and I am removing this console log so yeah I am clicking on Umar Khan and this is here set now go to the terminal and there is chat box and we have successfully retrieved in the fetch messages over data so basically data contains only one message the sender ID with the chat ID and the text okay it's time to render this message in our chat box so there I have my chat messages chat box message is basically messages dot map and then for each message let's make an arrowhead function okay so basically this Arrowhead function is returning sub jsx so instead of curly braces I should write the these braces and there will be an empty node and then I am making a div okay so basically this div will have a random class name basically random not a dynamic last name so basically how I am going to give it some class name I will say if the message dot sender ID is equal equal to the current ID means if the message is sent by us okay basically there is the current user not the current ID so if the message is sent by us then give the class name of message with the on and if this is not the situation then simply give the class name of message let's format the code okay so this Dynamic last name is just for the styling purpose because I have declared two separate stylings who unfold the my own message and other from the messages centered by an other person centered by an other person okay so each side this div here I have a span inside this pen I will say message dot text means the text of the message and then pan and inside this pen I am having the message dot created at so this all should be inside the curly braces like this now let's save and here I have okay there is one problem that this created add date should not be look like this so to solve this inside my client side okay I'm making another terminal and I am going to the client side I am installing a package npm I time ago dot JS so let's install this and wait Force installation so here our time ago.js dependency has been installed successfully okay so at the top I am importing a function from time ago which is having the name format from time ago.js okay so what the format function basically do it will help us to get the difference between the current time and the time that is mentioned inside the created ad so if I just simply write as format okay basically inside the curly braces like this and then like this and now I should make this inside the round braces okay so yeah now if I just save this and have a result on Umar Khan and here you can see it's saying just now but the message was not created just now because here I just forward to write the key our message is saying six hours ago means now we are successfully differentiating between the current time and the time mentioned inside the created ad okay so after all of these divs at the end I have the chat sender so how I am going to make chat Center let's make a div with the name chat sender inside this I am making another day which will have the plus sign means if in the future you want to add the functionality of sending images and videos then it will be possible by using this plus sign but for now let's move on okay now I have to install one and other dependency and the name of this dependency is your ad react input Emoji okay basically by mistake the previous dependency I installed here timer.js I use the npm but you should not use the yarn and npm as I have used in parallel means in the same directory I am using the yarn and npm it will cause conflicts between your packages but for now anyhow it's working fine and but you should avoid this if we are using yarn then you should stick to the yarn and similar case for the npm now let's hit the enter button so my dependency has been installed successfully so basically react input Emoji will provide us the input okay means the input like one you have in a basic HTML in which you can type anything so similarly input emoji and let's close this and I have to import this now so Ctrl C and at the top I will say import from okay from react input Emoji like this one now let's save this and here for the input Emoji I am saying its value will be equal to new message and on change I will call a function like the handle change okay so now let's first make a use state of our new message so okay just simply just copy and paste this so just copy and paste this and let's say it as new message and then here set new message okay and at the start yeah means by default it will be a null string so let's save this and at the end of these use effects here I am making the handle change basically it's a very simple function like const handle change and in the parameter it will take the previous value of our new message and then the fat Arrow function and by following this it will set our new message as the new message okay so there should be only new message like this let's save this and see the results okay there's another new message is not defined so where new message is not okay because here I have made it new messages by mistake let's save again and still there is an error that set new message okay so okay I have to change it here again so here I have the input where the Emojis are enabled to send you can see messages you can write in alphabets and then you can add more emojis you can search for different type of images like dog and happy and anything you want so this is just basically a react dependency okay it's time to make a send button so here below this input Emoji I am making another div with the class name of send button and I am also giving it a class of button and inside the button I am simply writing send let's save here I have made the button successfully but this is not our predicted Behavior as I have selected no chat so this should not be rendered now there should be something like tap on a conversation to start conversation so for this here I will make all of this rendering depends on a condition below the chat box container I am saying if chat exists then return all of these things so I am just taking all these strings from here Ctrl X okay and then here Ctrl V and if it is not a case then in the else part I am rendering an other span okay so I have to make it manually like this and this pan will say tap on a chat to start conversation let's save this and see okay so now it's saying tap on a conversation so I adjust as soon as I tap so now the correct view is rendering so I have to style them so forth The Styling just giving them a class name chat box empty message like this now let's save and if I refresh so yeah it's working fine and I like to give three dots okay so now if I click on the marathon and here it's rendering the messages of Omar Khan It's Time to implement the socket dot IO in our project so let's go to the vs code and I am closing all the directories and I am making a new folder socket so basically socket initializes it's our own server it has nothing to do with the database means it will have no work with writing deleting or any type of modification in the database documents it just provide us a type of middleware and you cannot say it a pure middleware it's just giving us a way to inform the users in the real time that what actions are performing okay that's the talk enough talk now let's go into the action okay so I am making another terminal and here I am writing npm in it so it will ask some questions just press enter enter and enter okay so inside here I have a package.json so inside the socket I am installing a package socket dot IO and also node mod let's hit the enter button and wait for the installation so both the dependencies has been installed successfully now I am making a file inside the socket and the name is index.js but before making anything inside index.js I am opening the package.json inside the package.json I am just deleting this script and here mix start script which will work is not more index.js okay by the way we used not mon as a type of hot reloading on the server side we will not need to restart the server manually again and again when we change the files for our server okay so let's save this and this is our index.js site index.js make cons i o is equal to require socket dot IO and and then specify the port number I am giving the port number of 8800 and then give it a course origin so just like this it's a simple initial setup for your socket server as you did for the express server so our course will be the localhost 3 out 3000 where our react application is running as I mentioned you earlier it has nothing to do with our Express server or with that database it's just a type of communication between the users to users after this here I am making an empty array with the name active users means the users that have subscribed to this socket server okay so you will clear all of these Concepts as we further move on it's time to actually start the software server and it is started by writing IO dot on connection and then a socket will be provided and it will be a arrowhead function so our socket server is started by subscribing this connection okay so whenever someone is subscribed to the connection he or she can actually uses all the functionalities described under this connection so let's make it in a proper sequence so my first functionality is add new user means register a user on our socket server here I will say socket dot on new user ad like this this case State the parameter of new user ID that we will provide from our react side and then I am saying if user is not added previously to make this check I will say if active users so active users dot sum and for each user I am checking user dot user ID is equal to the new user ID that is sent in the parameter and if it is the case then we should not include that user in our previously active users so therefore here I am making a negation means if the user is not already registered to any of the socket then activeusers dot push the new user with the user ID that is the parameter and the socket ID is provided by socket connection itself it will always assign a unique socket ID so you don't have to take care of it manually and I will say IO dot emit get users active users so what basically emit works we will write the on when we have to take something from the other side and we write the imit when we have to send something towards the other side means we are taking a new user ID from the react client side therefore here I have made the socket dot on means it is a type of active event that is always active on our socket server side anyone can click this event of new user ad then these conditions will be checked and if the user is not already present in this array then it will be pushed by assigning a new socket ID and after doing all this work we will send a data towards the react client side and we are sending this data by writing IO dot Emit and get users active users so client side will get the data by writing get users so this was all the thing when a user is connected to the socket server I have to cover another aspect when someone is disconnected from the server so I will say socket dot on disconnect Arrowhead callback function I will say active user is equal to active users dot filter now for each user check the user ID if it is not equal to the socket dot ID and this socket ID is a specific one that is disconnecting from the server it is basically a default type of function inside our socket dot IO so therefore this socket ID is automatically captured from the client side that which user is disconnecting so here we have the ID of that user and here I am saying that from all the users filter out that specific user that is trying to disconnect okay so to more specific about this here I will say console log user disconnected yeah something like this and then the active users means the remaining active users will be shown here and at the last as similarly I have emitted the remaining active users so similar stuff I am doing here I am again emitting the active users towards the client side let's try this okay let's make an other thing if I also here make a console log and I am saying connected users active users let's try it and run our server by npm start the end to see the results on our terminal I have to connect it with our react application so I will go to the chat.jsx and here install a dependency so this this is our client side and here I am installing yard at socket dot IO client means the socket.io for the react client so now our dependency has been installed successfully and I am going to the chat Dot jsx and at the very top here first import our IO so I am saying import IO from socket IO client okay now I am making a reference for socket to use all around our chat application I will say con socket is equal to use ref and import it back to importing yeah something like this okay now let's make a use effect so use effect and this use effect will depend upon our current user that is connected so whenever it changes then use effect will again form and here I am saying socket dot current IO towards the localhost and our Port was 8800 now on the second step if I go to the index.js of our socket here I said on connection you can subscribe to the new user ad functionality and the disconnect that is an automatic functionality of a socket.io so basically we have to subscribe this new user ad socket functionality so to subscribe for a specific event we have to write the image therefore I am writing current dot image and I have to emit the specific event if I'm just copy and pasting it and give the user dot ID as the parameter that we will receive here inside the new user ID and all of these things will be performed automatically so let's revise this in a sequence the condition will be checked if it is not present already then it will be inserted in the active users array then it will be console log to our terminal and after this it will be emitted towards our client side so to catch these imitate active users on our client side here I am writing socket dot current dot on get users as I have made event on the index so users and function like this and I will say set online users as the users of course I have to make a use date for the online users therefore I will say const online users and then set online users equal to the U State and at the start the array will be a null array so that's enough let's control s and have a look on our socket server here you can see our first user is successfully console log mean pushed in the active users array means the Zen ID that's currently enabled here is successfully submitted to the socket.io now we also have to check the online users on the client side if they are retrieved successfully or not so let's close this and here I am saying console log online users yeah now let's save this so basically there is only one active user and this is the socket ID and this is the user ID means it's also working fine on the client side now just simply remove this console log message it's time to send messages to another person and store the message in our mongodb and also send the message in real time towards the second person so I am going to the chatbox.jsx and here on my button there was a button okay here I'm making an on click event on click handle send now just copy the name and yeah here is the perfect place to make the function like this in the parameter it will take the event now first of all even dot prevent default okay let's just skip this for now make a message object so I will say const message will be equal to the sender ID which is the current user and the text which will be equal to the new message as we have stored in the U State and the chat ID will be equal to the chat dot ID that is coming from the props it's time to send it towards the mongodb so I will say send message to database okay let's make it like this one and then we have to make a try catch block and for the catch just simply console log the error and inside that try block I am saying cons data is equal to await add message the message will be sent as props towards the message request and then set new message as the empty string but with the data I also have to make the set messages as the previous messages spreaded by the spread operator like this and the new messages will be added in them okay so I have to make it async to use the await functionality and now I have to make the add message request inside the message request so I will go to the message request dot JS and here right export cons add message it will take data as the parameter and then simply the API dot forced towards the message okay there should also be a backslash like this and send data as the request dot body now let's save this and here import it from the request like this Also let's save this and try on the front end if I make a new message hello Umar and send this then there is the new message and now I have to check the database by refreshing I will go to the messages and there are two messages the second message is the hello mode that I have sent just now message request was the mongodatabase is working fine let's send the message in real time towards the second person because if now I am just logged in by the incognito mode it was the local out 3000 and then the Umar at the rate gmail.com and then Umar and if I log in so inside the chats the Zen RK and you can see that if I make a new message here I am fine and if I send this then it will not be mentioned in the Zen's ID here you can see there is no new message if I refresh then it will be added because the new data has been fetched from the database but we want to chat in real time here I am saying send message to socket server for this first I have to go chat Dot jsx and here I am making a new use State forms send message and set send message like this with the use state of final at the first and then I am sending this set send message as a parameter towards the chat box so this is the chat box and set send message as the prop let's close this now let's see if this inside the chat box so at the top I am receiving it like this and inside the handle send now here I can use this function first of all I have to declare the receiver's ID because in the index.js I will send the message towards a specific user using the receiver's ID so const receiver ID will be equal to chat dot members and inside the members find the ID which is not equal to our on ID means the receiver ID and then set send message equal to the message that is already available and add the receive receiver ID okay so I think I should make this like this now let's save this and inside the chat.jsx I am making an other use effect so okay there are some things like the online users and the send message let's make an other use effect so I am saying use effect and then this use effect will depend on the send message first of all let's check the message condition if the current message is not equal to null then perform some functionality and the functionality is Socket dot current dot emit send message like this with the parameter of send message now I have to make the socket dot on on the socket server side so on the index.js here after this I am saying send message and this will be equal to socket dot on send message and it will take some data as a callback function parameter first of all it will be structure the receiver ID from the data like this one and then find the user cons user is equal to activeusers dot find for each user if the user dot user ID is equal equal to the receiver ID so basically here what I am doing finding a specific user from the active users whose ID is the receiver ID in short I am searching the receiver inside the active users and to confirm this also console log this so I am saying console log sending from socket towards the receiver ID like this and also console log the data so console log data is equal to the data and now I say if the user exists means if the user is currently in the active user then io2 user dot socket ID dot emit receive message data okay basically what this function is doing here this saying if this is a real user inside the active users then we are just simply consoling some data and then I am checking if the user exists then to a specific socket ID as you know that inside the active users when I was pushing a new user I was also pushing a newly generated socket ID so I am taking the socket ID from that user and I am sending a new message with the event received message and the parameter is all the data we have inside the data we received from the client side and this is an emit function because now we have to send data to an other side okay as we are sending the data to an other side we have to receive it on the client side I will say on the chat.jsx I am making and others use State just copy and paste this and okay that's modified as receive so receive like this and now make the r capital it's time to make an other use effect so I should comment out all these effects so send message to the socket server okay so the socket server and similarly receive message from the socket server send message from socket Etc it will be again a huge effect that will depend upon our receive message you state so receive message and here I will say socket dot current dot on receive message like this one the data as parameter and set receive message but I think so that it should not depend on the receive message because I want to render it every time it exists so by making this dependency as the receive message we will not able to get the data in real time so let's just remove this and save it and to make these changes available on our chat box I have to send it as the parameter towards the chat box as received message is equal to the received message okay like this okay so I should copy and paste it like this I'll catch this prop inside the chat box so here I am saying receive message received like this and let's make an other use effect for this and now this use effect will depend upon the received message okay so our chat box will be rendered again when the receive message array is changed so first of all I will check if the receive message is not equal to the null and receive message.chat ID is surely equal to our current chat ID in this scenario we only have to do one thing which is the set messages equal to the previous messages like this and the receive message okay let's format it all again and I think now we have set up all the things correctly let's try it okay first of all our application has been crashed because for a long while we have not tested it okay let's refresh it and see where is the error so guys I reviewed my all the code and there were only small mistakes during the code that first of all the use effect we have made here to receive a message should be after the initialization of our socket here because as you know we are initializing our socket with the address in this use effect so first it will initialized here and then our receive message socket will be on okay this was our first mistake and after this as you know that here the receive message is sending as parameter towards the chat box here you can see that this is our parameter r e c i e v e and when I am receiving this parameter inside the chat box here you can see there is a typo so I have to fix this so I am just now copying and pasting the correct spelling like this like this like this and similarly for here okay basically these console log I made just to check the code and you can easily skip them as this now let's save it and I have already saved this let's see here if I now send a message let's first refresh so as you can see now it's not crashing and if I send message how are you and let's send this now on the other end on the umer's end here is the message how are you you can check it by side by side let's see I am fine so as soon as I send there is a message I am fine how cool is this okay it's time to make our chat box div to automatically flow towards the last message as you know now we have to manually scroll it towards the last message but this is not our predicted Behavior we have to make it automatic so to make it automatic I will go to the chat box and first of all here I will make a used ref I will say cons scroll is equal to use ref and then Auto Import it from react no I I will go to the message deal so where is our message deal let's check here okay yeah that was the day for our message here I am saying reference is equal to scroll yeah okay just delete this is extra okay so now I have to make a huge effect that will always scroll it towards the last of our page so here I am making comment always scroll to the last message yeah like this uh use effect and then inside the EU reflect scroll Dot current and if available then scroll into view and this is a very basic trick trick you can easily find it anywhere on the internet this is not a too much highly conceptualized thing this is a very common trick and very old one to scroll the pages towards the last div okay so here the dependency array will be the messages means whenever the message is in our chat box will be changed then it will be scrolled down towards the last message so if I check now again here I am saying what plan tonight like this if I send this and here you can see both divs are scrolled down towards the last message automatically so overall functionalities are covered now but we should also check by sending the Emojis because we have not tested it yet okay it takes some time for the for loading all the Emojis on the first render okay now let's send this emoji and here it is sent and is also received properly so very cool it's time to make the functionality of online and offline status working because now if I just offline the umer still it will be shown as online because we have hard coded the online dot as you can see if I disconnect it still it's online okay here you can see it's online so how we are going to manage it as if you know in the index.js when someone is connected to the active users mean the active users array someone is added then we are also emitting the get users even towards the client with the data as active users so now we have to receive this data inside our chat.jsx so I am going to our first use effect here okay so as I am receiving the data inside the get users and setting the online users so now I have to render the online dot on the basis of these online users so what I will do I am just simply making a function okay so here I am saying const check online status and the parameter will be as the chat okay inside this I will say const chat members will be equal to chat dot members dot find where member is not equal to the currently logged in ID okay so here first of all I have extracted out the other member inside the chat after this I will say const online users find and then for each user check if the user dot user ID is equal to the chat DOT number I will explain this totally for you and then return online if it is then sent true and if it is not then send false okay so here I have made a function to check the online status and I am sending the current chat as a parameter so basically where we are going to use this function we're going to use this function inside the conversation so this is the conversation and here I am saying online is equal to check online status and send the current chat as this is the part of iteration towards this function means during the iteration we are trading through e-chat and then for each chat I am checking the online status of that specific person conversation so yeah here I have extracted out that member from our chat means the one person should be myself and the second one is the other one so I have extracted out the other person and now I am checking if the online users includes that other person and if it included then we will send online as true otherwise as false okay now receive this prop on the other side so I am this copying online prop to write the previous mistake and go to conversation.jsx yeah right here and here I am going to receive this prop as like this and there was a Divya online dot if online is true then make a div like yeah this one so here should be dot now let's save this and have a look okay there is an error because nowadays noted like this and there is also an error that cannot resolve URL in conversation so module not found okay that was because here I have just imported this one and now it's working fine okay so okay it's saying online and why it's saying online because okay we are not seeing the online dot which is good but still it's saying online okay first of all day should not be anything and this pen should also be rendered on a condition so what I will do here I will say if online is true then send the string of online otherwise say it as offline yeah okay let's close the logic and now save here you can see now it's saying Umar Khan offline if I log in from his ID in an incognito window localhost 3000 and let's login as number gmail.com Umar let's login and I am going to its chats and here you can see now it's online so it's saying okay let's make it here saying Zen RK online and he is saying Umar Khan online now as soon as I remove this one then here you can see it's offline now so how cool this is the functionality so our total functionality is related to a chat applications are completed now I hope you like the tutorial very much so if you really learned something new by today's tutorial then please hit the Subscribe button and don't forget to share this video with your friends and many more let me know your thoughts about this tutorial in the comments I will meet you in some other tutorial till then goodbye
Info
Channel: ZAINKEEPSCODE
Views: 78,652
Rating: undefined out of 5
Keywords: zainkeepscode, reactjs, react, website, react website 2022, for beginners, socket io, socket, react socket.io, react chat app, MERN, mern stack, mongo db, realtime chat, app, socket.io node.js tutorial, socket.io chat app, socket.io chat application, socket.io real time chat, socket.io chat room, socket.io chat tutorial, chat application in react js, chat application node js, real time chat application using node.js, react chat application, real time chat application tutorial, mongod
Id: SDMs2Pq6w90
Channel Id: undefined
Length: 108min 25sec (6505 seconds)
Published: Sat Jun 18 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.