Django & React Tutorial #9 - ComponentDidMount and Django Sessions
Key Takeaways
This video tutorial demonstrates the use of React lifecycle methods, specifically componentDidMount, and explains how Django sessions work, including adding and deleting information from sessions.
Full Transcript
[Music] hello everybody and welcome to video 8 in this django and react tutorial series what we're going to be doing in this video is kind of starting from where we left off we're actually going to be working on the home page we're going to be trying to make it so that we can actually redirect the user to the room that they're currently in if they leave the website and then rejoin it so pretty much we're going to be styling this home page actually making it look better than just a paragraph tag that says this is the homepage we'll have a button that says join a room we'll have a button that says create a room based on what they click they'll get redirected to those different pages and then if the user is already in a room for some reason say maybe they left the website and came back to it will automatically redirect them to that room so that will mean in the next video we'll have to actually code out some more stuff on the room page itself which will allow a user to leave the room so that they can you know get into another room or create a room of their own anyways we've got a lot of stuff to do a lot of cool stuff still to come in this series i hope you guys are excited let's go ahead and get started so the first thing that i want to do is i actually want to start working on the home page and just coding out what this should look like so pretty much we're going to have this route right here which is the home page and well we need to look better than this paragraph tag now i'm actually going to put everything that i want to render here inside of a separate method or a separate function just because it will be a little bit easier if we can have it kind of separated for what we're going to do next but anyways let's make a method and let's just call this render main section or you know we can even call this render home page like that that makes sense as well inside of here we don't need to take anything and we'll simply return some brackets like this and then inside of here what we want to render we'll just call this function from inside of this render function and then it'll give us all that html or the jsx or whatever you want to call it anyways we're going to need to use a grid we're going to need to use typography we're going to need to use some buttons so we need to import all of that so let's go up here and i'll actually just do it above react router dom and i'll start by saying import we're going to import the grid we're going to import the button we're going to import a new thing that i don't think we've used yet called button group and then we are also going to import typography now that is all going to be from at material ui core all right so now that we have all that let's go inside of here and let's start setting up what we want so the first thing that i want to do is just make a grid this is kind of standard just to make sure everything's nice and centered so we're going to say grid we're going to make this one a container i'm actually gonna say the spacing is equal to three and then i'm gonna close the grid tag like that now inside of this grid we're gonna make two grid items one for pretty much each thing that we're gonna have so we're gonna have a big title this title is going to be kind of the name of our app i'm just going to call it house party but you can call this whatever you want feel free to change the name and then we'll have another grid item and this grid item will store the two buttons i want to have two buttons horizontally aligned one that says join room and one that says create a room anyways you'll get it as we go through but let's make the first grid item so if i can spell grid correctly we'll say grid item xs equals 12 we will say align equals center like that and then close the grid now we can just copy this because we'll use this again down here and in the first one we want to put our title so i'm going to go ahead and do a typography tag like that we're going to say that the variant is equal to h3 so a little bit bigger than what we've been using before which was h4 and then we'll say the component is equal to h3 as well now we can end the typography tag and inside of here we'll just put what we want our title to be now i said that i wanted to call mine house party so let's go ahead and do that and call this house party nice now inside of the next grid we want to set up a button group the reason we're setting up a button group is because we want to have two buttons aligned horizontally and this is just the easiest way to do this it's literally the tag is just called button group and it will take the two buttons based on kind of the stuff that we give it and make sure that they are aligned horizontally all right so inside of here we're going to do our button group so we're going to say button group we're actually going to write this thing called disable elevation if you want to see what it looks like with elevation you can just remove that tag but pretty much this is just going to remove kind of the shadow that by default is showed up that i don't want then i'm going to say variant of this is going to be equal to contained this will make sure that we're aligning them horizontally and then the color for this for our button group we can make it equal to primary although it doesn't really matter what we have for that all right so now we have button group here now we're just going to define two buttons we've already done this before many times we'll say button we'll start by defining the color this one will be primary and then we'll say what do we want this button to go to well we want this to go to the slash join page then we'll say what component is this button well the component is going to be equal to inside of our little squiggly brackets like this it's going to be equal to a link which we have imported up here all right awesome uh so then we can just close the button actually i guess we'll just do a full button like that and then inside of here we'll do our name and we'll say join a room okay and it's going to copy this we'll keep it inside of the button group because we want these grouped obviously the next one instead of being primary is going to be secondary like that we don't want to go to slash join we want to go to slash create this too will be a link and then instead of join a room we can simply say create a room alright so now we actually have the render for our home page we can take this and just use it inside of this render method so inside of here it's going to put two squiggly brackets and say this dot render home page and now whenever we go to slash we should call this function or this method we should show all of this jsx slash html all right so let me go to my browser let me refresh and you can see that now we get house party join a room and create a room now some of you may have noticed that sometimes i'm right clicking on this reload button in google chrome and i'm pressing empty cache and hard reload i'm messing with like a bunch of different versions of this application because i coded out before the tutorial to make sure everything looks good so sometimes the caching is all weird if for some reason you guys are updating stuff and you're not seeing it in your browser if you're on google chrome just make sure you open up the inspect window so you have to have the console open and then you can right click on here and click on empty cache and hard reload anyways let's make sure this is working i'm going to press on join a room brings us to the joy in a room page let's go back create a room brings us to the creator room page let's go back awesome that's perfect this is working and that's what i wanted for my home page now what i want to do is make it so that if we go to the home page and we're already in a room it automatically redirects us to that room so to actually accomplish this what i need to do is pretty much right when this application loads or right when this home page loads i need to check if the user is currently in a room and if they are in a room then i need to redirect them now to do that we need a way to check if they're in a room right so really we need an endpoint that we can call on the server that tells us hey is this user in a room if they are what room are they in and then from here we can redirect them to that room so i'm going to start by just creating what is actually going to be kind of the entry point for this now i don't think i've talked about these before but in react there's these things called life cycle methods now essentially these are things that you can kind of hook into that allow you to alter the behavior of the component so the life cycle method that we're going to be using this is called component did mount so we will continue in one second but i need to again thank the sponsor of this video and the series which is algo expert algo expert is the best platform to use to prepare for your coding interviews at large tech companies and they recently released an awesome new feature which is mock interviews on the platform so you can actually sit down and perform a mock interview with another live human being which is always some great practice if you guys want to check out algo expert have a look at it from the link in the description and use the code tech with tim for a discount on the platform so componented mount pretty much means that the component just rendered for the first time on the screen there's a bunch of different lifecycle methods i'm not really going to go through them in depth here you can look them up if you want to see what they are but there's pretty much are just ways to hook into the behavior of this react component so if you want to do something before it loads or before it actually renders on the screen well then you would do that in a specific life cycle method if you want to say make the component not update when something specific happens then you would hook into the should component update method or hook or whatever you want to call it and just say hey no we shouldn't update if this happens there's a bunch of different things you can do they actually are pretty important to understand and we'll use more of them as we go through this tutorial but for right now we're just going to use component did mount now some of you may be noticing that i put this async keyword here uh we will need to use that i'll discuss why in a second but but usually when you do a component mount you don't have the async before it the reason we're going to have async before it is because we're going to be performing an asynchronous operation inside of component did mount now if i don't put async here in case you're not familiar with what async means if i don't have that keyword here that means that whatever i put in this method we need to wait for all of that to happen before we can do anything else and pretty much what we're going to do inside of here is we're going to call an endpoint on the server and that could take some time right imagining these things are not on the same device maybe the client is sitting you know halfway across the world this could take like a second or two or maybe even just like a few milliseconds to load so we want to make sure that the rest of our application isn't waiting on this component did mount method and that only once this is ready to go it actually performs the action inside of it so if we put async here that pretty much tells the program that hey this is asynchronous which means we don't need to wait on this to finish before we can go ahead and continue doing other things in the program but as soon as this is ready to go or as soon as we actually receive a response from the server and we'll see that in a second then we'll go ahead and actually execute what's happening inside of there anyways i hope that kind of makes sense as i said and as i keep saying it will make more sense as we go through but i just feel like i need to explain that in case some of you guys are wondering all right so now that we have that uh let's actually go to the server and just make our end point this one's going to be really simple and then we can call it and then we'll actually be done for this tutorial so what i want to do is create a new view here and i'm just going to say class and this one i'm just going to call user in room again feel free to call this whatever you want but we're going to inherit from api view and all we want to do in here is simply we're just going to send a get request to this endpoint uh and then the endpoint will check hey is the current user in whatever session they're in uh are they in a room and if they are then we will return that room code so i'm just going to define get like that i'm going to say self request and then format equals not for nat format equals none like that and then here i'm going to say data equals to and then we're just going to do a blank python dictionary we're going to say code this is what we'll use as i guess the key for returning our actual room code and then we'll say that's equal to self dot request dot session dot get and then room underscore code now notice this is the same thing that i'm using inside of here right when i actually update the user session and add that information telling us hey what room this user is actually in so it probably would make sense to actually make kind of a global variable at the top of this file that says you know room code field or something and then we put that inside of all of here so they're consistent but for now it's fine we'll just leave it as a string room code so this is how you get information from the session if there is no room code it will simply return none now there is one thing that we need to quickly do inside of here we need to make sure that the user actually has a session so we're going to do the exact same thing that we've done previously we're just going to take this right here and put this at the top of our function here at the top of our method just to make sure that we actually do indeed have a session because if we don't have a session well that is problematic so now that we have that what we're going to do is we're simply going to return a json response now we have not used this yet so i'll discuss it in a second what this does is take a python dictionary and serialize it using a json serializer and then sends that information back to the frontend or sends it in the request so just like we had you know this uh i guess room serializer right it's the exact same thing except we're just going to take an arbitrary python dictionary rather than a python object like a room or you know like database models that we had so let's go to the top of the file here we're going to say from django dot what is it here i think it's http we're going to import json response like that so there we go we have json response and now all we have to do is instead of json response we're going to pass the data that we actually want to send and then we need to pass the status code so we're going to say status equal status dot http underscore 200 underscore ok again remembering that if they're not in a room we'll simply return none so we can handle that case on the front end where we say hey you know user is not in room so we aren't going to redirect them all right now we need to set up the url for this so let's go to urls.pi let's import user in room like that and now let's make our path so we're going to say path i guess we can call this user in room i mean i guess that makes sense that's what we call to the class and then that will be user in room dot as underscore view all right so now we have our url uh we have our api endpoint all that's left to do is actually call it and then kind of handle the logic or handle what happens based on the response that we get so let's go back to our home page now inside of here i am simply going to actually fetch or send this request so that we can get if the user is in the room so i'm going to fetch slash api slash user hyphen in hyphen room remember not to add the trailing slash otherwise that's going to cause an issue we're then going to say dot then here we're going to take a response and we're going to return the response dot json like that and this will have to have parentheses we're then going to say dot then one more time here this is going to take data and then what we're going to do is actually something that i've not yet talked about but let's just save that and get that going so what's going to happen right now is we're going to call api user in room this is going to return to us whether or not we are in a room and if we are in a room we are going to actually get that room code coming in through the field called code and then what we'll do is we'll return the response.json so we'll just get the json from our response that will then go to this dot then so now we'll have data which is really just a json object then we can parse and look through this json object and pretty much get the room code so what i want to do is i want to store this room code in the state of this home page and then i want to use that inside of my render method to determine whether or not i need to redirect us to another page so you'll see kind of why and how this works but let's start by just setting some state so we're going to say this dot set state like that and that's going to be equal to room code and by default this will be no so now we have some state so what we'll do inside of this dot then that we haven't yet written is we will say this no not touchless what i'm saying this dot set state and then in here we'll say room code is equal to data dot code now if for some reason the or i guess if in the situation where this code is none we will just update room code to be equal to null once again so that would be totally fine and all will still work all right so now that we have that what we can do is actually use this state inside of our render method and remember that pretty much the way this component.mount is working is once we've rendered the page so we've actually already called this render method one time we will asynchronously do this operation so once this is done and this has completed we will have set the state and this setting of the state will force our component to re-render so once it re-renders then we'll say oh we have a new room code down here we'll see that we have a new room code and we can go to that room code because by default when we start this application the room code will be equal to no so on the first render it will show us the home page and then after this component.mount is finished running we'll see hey we have a room that we're actually in we need to go to that and then it will redirect us there based on the logic that i put inside of render so inside of render what i'm going to do is kind of you do a weird thing here but i'm going to go inside of my route for the home page and pretty much i have two cases right i have the case where we're in a room and the case where we're not in a room so i need a way to tell us whether hey you know we redirect to the room or we just show the contents of the home page so i'm going to say render this is actually a guess i guess a method or something that you can hook into and you can change what happens when this route is rendering something right so here we have component is a room join page here when i define render this just means that if we're on this route it will call this render method whatever we put inside of here is what's going to show up okay so i will actually remove this here and now what i want to do is inside of render i need to make an arrow function this is because whatever i put inside of here this is the function that's going to be called when i'm rendering this route so if we are actually on this route then we will render whatever or we will call this function which will then return to us whatever we should render so inside of here i've done an arrow function i open up my parentheses again now i'm going to return and we're going to actually use the ternary operator here to check if we have a room code or not so i'm going to say this.state.room code question mark in the situation where we actually do have a room code then what we need to do is we need to redirect to that room code so i'm going to put parentheses here and we will redirect in that situation and then i'm going to say colon and in the colon i'm just going to say this dot render render home page yeah i think that's what we called it right this star render home page yeah this dot render home page now for some reason that's giving me all kinds of issues let me just wrap this oh i think it's because i didn't put something here okay so i don't know what's going on but i think it's just because i haven't actually finished writing what i need to put inside of here but anyways what we're going to do inside of these parentheses here is we're just going to say redirect and we're going to redirect to and then inside of here we're going to have to actually grab the room code and redirect to that so oops not a zero we'll say two and then we'll use our back ticks like we've done previously and we'll go to slash room slash dollar sign open the curly braces and then this dot state dot room code so now what will happen is if we are in the situation where we have room code we'll simply have this redirect component which will just redirect us to the correct page now again i don't know why i'm getting this weird syntax error so let me just have a look and then oh it's because i did not end this redirect tag okay so now that i end that there we go now it's all working so pretty much what we have is if we have a room code redirect to that otherwise simply render the home page now i think that is all good and now what we need to do is uh actually just see if this is working so that should be it let's have a quick refresh here you can see i was looking at this component did mount to make sure that i was telling you guys the right thing let's close that let's refresh empty cache and hard reload and what's going on here do we have any issues in the console doesn't look like we do but we can see this is just loading like crazy and just constantly loading and what do we have here uncaught type cannot read property room code of null okay so let me just have a quick look and see what's going wrong here and i will be right back all right so i found what the issue is apparently i had this dot set state equals if this really should be this dot state equals uh so my apologies about that just an issue in the constructor here and that was causing us to have a problem so let's give a quick refresh here and now we can see that this actually does redirect us to the room so if i go back to the home page you can see that it flashes for a second that uh that home page and then it redirects us over here so let's actually just go to slash join and then we can go back and we can see that boom automatically redirects us back to the home page now or sorry not the home page but to the room page that we're in now we probably don't want that behavior exactly to be happening but pretty much what we're going to do now or in the next video is we'll add a button and we'll add some kind of nicer styling to this page that will let us actually leave the room so then we'll again send a request to the back end it will then remove that from our session and then that way when we go back to the home page it doesn't you know flash and then show us this it just keeps us on the home page so anyways that was all i wanted to show you guys in this video that's how we can use the user session to actually redirect them to the room that they're in so now say you know i close this tab and i go back to that this page it just automatically brings me into the room so i don't need to press the code again i don't need to rejoin and that way it's just more convenient say you know like you close your safari app on your phone the example i keep giving and then you open it back up you're already in the room you were in before all right so we're making some really good progress on this app again i hope you guys are learning a lot uh and you're excited about what's coming in the future of this series because i definitely am so with that said if you enjoyed make sure to leave a like subscribe to the channel and i will see you again in another youtube video
Original Description
In this django and react tutorial video I will be showing how to use react life cycle methods, specifically componentDidMount. I will also be explaining how django sessions work and how to add and delete information from django sessions.
💻 AlgoExpert is the coding interview prep platform that I used to ace my Microsoft and Shopify interviews. Check it out and get a discount on the platform using the code "techwithtim" https://algoexpert.io/techwithtim
📝 Series Code: https://github.com/techwithtim/Music-Controller-Web-App-Tutorial
◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️
💰 Courses & Merch 💰
💻 The Fundamentals of Programming w/ Python: https://tech-with-tim.teachable.com/p/the-fundamentals-of-programming-with-python
👕 Merchandise: https://teespring.com/stores/tech-with-tim-merch-shop
🔗 Social Medias 🔗
📸 Instagram: https://www.instagram.com/tech_with_tim
📱 Twitter: https://twitter.com/TechWithTimm
⭐ Discord: https://discord.gg/twt
📝 LinkedIn: https://www.linkedin.com/in/tim-ruscica-82631b179/
🌎 Website: https://techwithtim.net
📂 GitHub: https://github.com/techwithtim
🔊 Podcast: https://anchor.fm/tech-with-tim
🎬 My YouTube Gear 🎬
🎥 Main Camera (EOS Canon 90D): https://amzn.to/3cY23y9
🎥 Secondary Camera (Panasonic Lumix G7): https://amzn.to/3fl2iEV
📹 Main Lens (EFS 24mm f/2.8): https://amzn.to/2Yuol5r
🕹 Tripod: https://amzn.to/3hpSprv
🎤 Main Microphone (Rode NT1): https://amzn.to/2HrZxXc
🎤 Secondary Microphone (Synco Wireless Lapel System): https://amzn.to/3e07Swl
🎤 Third Microphone (Rode NTG4+): https://amzn.to/3oi0v8Z
☀️ Lights: https://amzn.to/2ApeiXr
⌨ Keyboard (Daskeyboard 4Q): https://amzn.to/2YpN5vm
🖱 Mouse (Logitech MX Master): https://amzn.to/2HsmRDN
📸 Webcam (Logitech 1080p Pro): https://amzn.to/2B2IXcQ
📢 Speaker (Beats Pill): https://amzn.to/2XYc5ef
🎧 Headphones (Bose Quiet Comfort 35): https://amzn.to/2MWbl3e
🌞 Lamp (BenQ E-reading Lamp): https://amzn.to/3e0UCr8
🌞 Secondary Lamp (BenQ Screenbar Plus): https://amzn.
Playlist
Uploads from Tech With Tim · Tech With Tim · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
A* Path Finding Algorithm(Visualization)
Tech With Tim
Python Programming Tutorial #1 - Variables and Data Types
Tech With Tim
Python Programming Tutorial #2 - Basic Operators and Input
Tech With Tim
Python Programming Tutorial #3 - Conditions
Tech With Tim
Python Programming Tutorial #4 - IF/ELIF/ELSE
Tech With Tim
Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Tech With Tim
Python Programming Tutorial #6 - For Loops
Tech With Tim
Python Programming Tutorial #7 - While Loops
Tech With Tim
Python Programming Tutorial #8 - Lists and Tuples
Tech With Tim
Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Tech With Tim
Python Programming Tutorial #10 - String Methods
Tech With Tim
How to Overclock a NVIDIA GPU
Tech With Tim
Python Programming Tutorial #11 - Slice Operator
Tech With Tim
Python Programming Tutorial #12 - Functions
Tech With Tim
Python Programming Tutorial #13 - How to Read a Text File
Tech With Tim
Python Programming Tutorial #14 - Writing to a Text File
Tech With Tim
Python Programming Tutorial #15 - Using .count() and .find()
Tech With Tim
Python Programming Tutorial #16 - Introduction to Modular Programming
Tech With Tim
Python Programming Tutorial #17 - Optional Parameters
Tech With Tim
Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Tech With Tim
Python Programming Tutorial #19 - Global vs Local Variables
Tech With Tim
Python Programming Tutorial #20 - Classes and Objects
Tech With Tim
Cool VBS Script to Prank Your Friends!
Tech With Tim
How to Overclock an AMD GPU
Tech With Tim
Best GPU'S For Mining Ethereum (2018)
Tech With Tim
Recursion and Memoization Tutorial Python
Tech With Tim
Ethereum Mining Rig - Hardware Guide
Tech With Tim
Pygame Tutorial #1 - Basic Movement and Key Presses
Tech With Tim
How to Install Pygame (Windows 8/10)
Tech With Tim
How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
Tech With Tim
How to Mine Ethereum 2018 - WORKING (Super-Easy)
Tech With Tim
Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Tech With Tim
Pygame Tutorial #2 - Jumping and Boundaries
Tech With Tim
Pygame Tutorial #3 - Character Animation & Sprites
Tech With Tim
Pygame Tutorial #4 - Optimization & OOP
Tech With Tim
OBS Studio Tutorial - Best OBS Settings
Tech With Tim
Linear Search Algorithm - Python Example and Code
Tech With Tim
Make Any Mic Sound AMAZING! (WITH OBS)
Tech With Tim
Binary Search Algorithm - Python Example & Code
Tech With Tim
Pygame Tutorial #5 - Projectiles
Tech With Tim
Pygame Game - Mini Golf
Tech With Tim
Pygame Tutorial - Projectile Motion (Part 1)
Tech With Tim
Pygame Tutorial - Projectile Motion (Part 2)
Tech With Tim
Pygame Tutorial #6 - Enemies
Tech With Tim
Pygame Tutorial #7 - Collision and Hit Boxes
Tech With Tim
Pygame Tutorial #8 - Scoring and Health Bars
Tech With Tim
Cloud Mining vs. Hardware Mining - 2018
Tech With Tim
How to Install Pygame on Mac OSX (Fast-Simple)
Tech With Tim
Pygame Tutorial #9 - Sound Effects, Music & More Collision
Tech With Tim
Pygame Tutorial #10 - Finishing Touches & Next Steps
Tech With Tim
How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
Tech With Tim
How to Create a Button in Pygame [CODE IN DESCRIPTION]
Tech With Tim
Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Tech With Tim
Pygame Side-Scroller Tutorial #2 - Random Object Generation
Tech With Tim
Pygame Side-Scroller Tutorial #3 - Collision
Tech With Tim
Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Tech With Tim
How to Create A Message Box in Python - Tkinter
Tech With Tim
Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Tech With Tim
How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
Tech With Tim
Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Tech With Tim
More on: JavaScript Fundamentals
View skill →Related Reads
📰
📰
📰
📰
Compile HTTP Error Indexes From Exception Classes; Humans Own Recovery Copy
Dev.to · Avery Lin
JavaScript Map: Store and Find Values Using Keys
Medium · JavaScript
Auth Middleware Should Not Guard Payment Webhooks
Dev.to · Gumbo Sveins
Common Server Action and API Route Errors in Next.js (and How to Fix Them)
Medium · Programming
🎓
Tutor Explanation
DeepCamp AI