How to send data from React js to Django app with Django Rest Framework on a simple example

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome back to the channel so my latest video on react and Jango received some pretty good statistics and this is why I've decided to make a continuation of this particular video so in this lesson we will learn how to send data from reactjs to Jango and how to update the page in an effective way before we begin just a short advertisement if you're a beginner to Django you can check out my Jango with tailon CSS udm course it's not for absolute beginners so some knowledge of python as well as the absolute basics of Jango are required if you're interested the link with the coupon code is in the description below before we start to code there are two things that I want to mention the first one and most important is to watch the previous video on how to connect Jango and react because this video is going to be the continuation of that particular tutorial so this is number one number two is that we are now going to walk through what have I done so far in the project and as you can see over here we have the products app so we will be working not with the posts but with products and when I show you the product class I would like you to stop the video and try to create your product serializer your product view set as well as register the view set in the URLs py so first of all let's take a look at the settings py file so I'm in the backend application and as you can see in my directory project directory I have backend which is the Jango application the front end which is react application and virtual environment so as mentioned before let's start with the settings py over here I have in the installed apps list the products application as well as rest framework I also have provided D Jango course headers and I have the setting course allow all Origins set to true so next let's go to the products let's open up the models py file and here is the product class so we have a very simple class with name description code and created fields and the code is generated automatically we generate it only once when there is no code so when we are creating our object and we are doing it with the use of ueid so this is the product class now you can pause the video and as mentioned before try to create the serializer The View set and register the um view set in the URL spy so I hope this wasn't a very big challenge you can create a product serializer by inheriting from serializers do model serializer with the use of class meta you just need to indicate what model you are referring to in our case it is the product class and you need to specify what FS Fields you are interested in so I listed all the fields except of created then let's go to the viewpi and over here we created a very simple view set we provided the query set which is product objects all and we indicated that the serializer class is equal to the product serializer then we registered our product view set with the use of the router next let's go back to core API URLs py and here we extended the main router registry with the product router registry the URL patterns for the API have also been included in the main URLs py file over here in the Jango Administration I created one product so let's maybe create another one and now let's go to the products and as you can see right now we have two objects test one and test two in the react application I didn't do much I've added the NV file providing the API URL as well as I went to SRC to Main jsx and I've commented out the react strict mode so now let's go to app jsx and let's first try to fetch the data so I'm going to remove everything from over here I'm going to remove also this count State and I'm going to remove the react logo the v logo and the app CS say I'm going to keep the use State because we will need it for later let's right before we fetch the data hello world and there we have it all right let's create a variable end point and this is going to be equal I'm going to open uh backticks over here so I can inject the V URL so I'm going to reference the Envy file with import meta envy and then the name of the variable like this and then slash products and then slash at the end all right so we have our endpoint and this is very important to know that over here we are be patching the data but also we will be sending the data as a reference to this particular end point because if we go back to our back end and we will open up the products go to API and to viewpi the view set helps us to manage the crow operations so we don't need to do anything else for the crow operations unless we would we would have some special requirements so in that case we would have to overwrite some methods but in our case we will be sending data to create new objects and the create method by default returns serializer data with status 2001 created so in our case we won't be uh we won't have to overwrite the create method at least not in this very basic example let's go back to app jsx and below the endpoint this time outside of the use effect hook I'm going to create a function that will be responsible for fetching the data from our API so this is going to be a async function and I'm going to Simply write now a response which is going to be equal a weit and I already installed axios so if you haven't installed axio just write npmi axio and then run the development server for the react up again so I'm going to import axos from axios all right so con response is equal to await axio get and we are going to provide the end point now we can also write maybe somewhere at the top console log patching because later I will want to reference this particular function to make a sort of an optimization you can say so now that we have the response we handled our promise we can simply get the data so we can do it like this data is equal to response data or we can destructure the data we can pick up the data from the response like this of course let's maybe console log the response and console log the data and finally let's read return the data like this now below this fetch data function I'm going to place in the use effect hook it got Auto imported as you can see over here and I'm going to initially run this fch data function like this so with the use of use effect hook we are handling side effects and and in simple words this means basically interactions with the external World such as patching data from the API so I'm going to save the app.jsx and I'm going to Simply right click inspect going to head over to the console and over here we have our data and the object that you see over here is our response so over here as you can see we have the data and we have the status 200 okay so as the next step let's create a state for the data so I'm going to create products data and a Setter for the products data and this is going to be equal use State and initially we will have an empty array so somewhere over here we can write set products data data and now we can display the products data so I'm going to head over to here and then I'm going to write products data map we are going to iterate through this products data and simply we will maybe do this in a unorganized list like this right and over here I'm going to display a list item so we need to provide the key for the parent element which is going to be the ID and over here we can Now display the element name so let's see see if this works or not I'm I saved the app.jsx and as you can see over here we have test one and test two all right and as you can see we have fetching at the top all right so now we can take care of sending the data so we will need a button and once the button is clicked we want to create a new object and then display it below the existing ones below the fetch data I'm going to create a new function called host data and it will also be a as sync function and Below we can Define first of all some variables we will need the name and the description because we want to create a new object so we need to provide the name and the description and in my case since this is a very simple example it's going to be a fixed name and description so I'm going to write Test X and then the description is going to be test description or Test X description something like this all right so once we have the variables that we want to send we can now create a body so body is going to be equal and then we will simply place in the name and the description description H I made a spelling mistake over here all right as the next step let's send the data using axio so we will have a response equal to await and then axio post this time we will will pass in the endpoint as well as the body which we are sending in order to create a new object with the name Test X and the description Test X description and then we can console log the response and then we can simply return response data like this all right so we have have our post data and I'm going to create a separate function which is going to be the Handler for sending data so I'm going to call it handle send data and this is going to be an async function because we will call over here post data and we can write new data which we created is going going to be equal await and then post data okay and basically later we will add some logic over here but for now let's go to our jsx and somewhere over here I'm going to create a button and I'm going to maybe give it a label click me or create data and on click we will refer to the handle send data okay so let's save this and let's see if this will work or not so I'm going to press create data and let's go to the console and as you can see we have a confirmation that the data has been cre created so over here we have the data over here we have the object with some Code test X description the ID and Test X and as mentioned before we have the status 2001 created so this comes by default with the create method of the view set all right so the problem right now is that we don't see this uh newly created object on our page once we refresh it it is over here perfect but in order to see it we need to reload the page so I'm going to show you two things that you can do in order to update the page one is going to be a little bit less effective the other a little bit more effective let's start with the less effective method which is a little bit simpler you can say so I'm going to copy this state base that below I'm going to call it refresh and then set refresh by default let's set it to false so whenever we send new data and create a new object um we can write right if new data then what we want to do is to set refresh to the opposite so we will have pref state and then we'll set it to the opposite and this this way we will render the page so I'm going to save this and press create data as you see we don't see any updates and this is because I forgot to do one thing and mainly we need to set in the dependency array refresh right so maybe before we do this I'll just console log refresh over here and then let's try it one more time create okay we see refresh now I'm going to remove this and then I'm going to add refresh to the dependency array let's save this and let's try it again and now as you can see we have our page updated however now we also see that each time we are fetching the data okay so we have one request to send the data and then another request to get the data and this is not the most effective way especially if you are dealing with large amounts of data um so yeah what we can do is to update the data on the front end so I'm going to maybe cut this basted below as a comment and I'm going to set this as a comment and set the state as a comment okay next inside of this condition if new data we are going to set the products data but first we are going to reference the PRI state or preve data I'm going just to write preve State and first of all using the spread operator inside of a new array I'm going to spread the existing objects okay so here we have our existing data you can say in this particular array but then at the end I'm going to add the new data like this so I'm taking into a new array my old data and adding to it the newly created object all right so let's see if this will work and as you can see everything is working but this time we don't see the fetching so we have one request to create an object and then um we are simply updating this on the front end so we can change this to test Z let's try it again and we have test Z over here so what you don't want to do is to place in the products data into the dependency array because as you can see you will create some kind of a infinite Loop right so let's keep this empty and just do it this way I recommend doing it this way if you have a different way please share in the comments below and yeah I think we can finish this video over here if you would like more videos on D Jango and reactjs working together please also let me know in the comments below I hope you enjoyed this video and hope to see you guys soon
Info
Channel: Pyplane
Views: 6,202
Rating: undefined out of 5
Keywords: how to connect django with react, how to send data from react to django, django react js project, django rest framework react, drf react js, django reactjs tutorial, django with react js, django with react frontend, web development, python django web development, react js with python backend, react js with python django, django rest framework, django cors headers, django react tutorial, send data from react to django, send data with axios, fetch data react
Id: iqlgr1AQt9Q
Channel Id: undefined
Length: 21min 46sec (1306 seconds)
Published: Mon Feb 05 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.