#1 - Build Quiz App in React & Asp.Net Core Web API with Latest Material UI

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
quick demo of this tutorial here we will build a beautiful quiz application with react.js and asp.net core web api with latest material ui5 this project is built from scratch so that you could learn all about full stack web development with react.js and asp.net core web api apart from creating a beautiful material ui interface you could learn best practices in using context api form design routing authentication in small application like this etc so please watch till the end of this tutorial and build your own quiz application so first of all let's start with creating react app inside this project folder here for that we have to open command prompt from this folder directory so you can use the shortcut inside this folder path here just type cmd then hit enter so here we have opened the command prompt from the same directory as that of this folder here now to create the react app you can execute this command npx create react app then name the application in small letters now before creating react or dotnet cover api make sure that inside the folder path directory here we don't have any special characters it might cause problems while running the application i had some similar experience in pass so make sure to avoid special characters inside the folder path directory here now let's execute this create react app command it might take a while so please be patient finally we have completed with the app creation command as a result of that here we have a folder with the same name as that of the react application now we have to get into this new folder quiz client now let's open the folder within vs code but that you can execute this code space then period or dot simple hit enter so here we have the brand new react application with default components now let's run this application for that open the terminal we can use this menu item here or you can use the shortcut ctrl shift then backtick then execute this command npm start it will compile and open this application in our default web browser so this is how the fresh react app looks like for designing this application i'll be using material ui components i have already created a material ui tutorial on this channel it was created with previous version of material ui soon i will be uploading a new version of the same the existing tutorial link is given in video description and inside the icard top right corner now let's look how to integrate material ui into our react application for that click on this get started button here first of all we have to install these libraries here so let's copy this command let's open a fresh terminal like this and paste it over here so here we are installing the core package of material ui these are two packages introduced in the latest version which is a styling engine in version 5. so here we have successfully installed the packages this documentation is recommending this roboto font so let's grab corresponding reference and let's paste that inside the index.html here let's paste it just about this head and tag here we also need material icons so let's copy this reference also and let's paste it over here now this index.html file has the html wrapping for the entire application inside this html we have this div with the id root this div is replaced within this index.js here which is the root javascript file for any react application you see the root div is replaced with the components passed here by default app component is shown inside the root div and here we have the app component and whatever we have here is responsible for the default view of the application here so first of all let me remove these default html from here and this logo reference also now let's quickly design a login form for this application first of all i will create a new folder here called components so that i will create this component login to create the component i will be using this snippet rfc react functional component in order to use this snippet first of all you have to install this extension this one here okay now click on this so here we have the corresponding component with the same name as that of this javascript file here login now let's show this component inside this app component here now while tapping the component you will see the suggestions and if you click on that corresponding import statement will be added at the top like this sometimes it may not work as you expected in that case you have to manually add the import statement up here okay now let's design a form for the login operation with name and email address for that first of all we'll be having an html form here to disable default html validation we can have this attribute now we need an input text box for that inside material ui you could see this component text field and components we need a text box that looks like this so we could do this text field i don't know why my auto suggestion is not working for material ui components so i will add the import statement here from material ui material we have to import text field first of all we have email so label will be email the name of the component now in order to look like this box here we have to set this variant property as outlined so here we have the text box inside that you could see the auto suggestion or the previous auto complete from previous posted data if you want to ignore previous posted data like this you could set this attribute auto complete as off like this we need one more text box for name now we need a submit button for that we have a component button you could see the same inside this menu here or you could also search inside this text box for that you can use the shortcut ctrl k so that you can easily find the component that you are searching for so let's search for button hit enter you could easily see the corresponding component document like this so here we have the button component while typing the component here you could see the auto suggestion if you can't like this just use the shortcut hold ctrl then press space then you could see the possible auto suggestion if you select the item corresponding import statement specified here will be added at the top so first of all type is equal to submit the variant will be contained size will be large all of these properties and attributes are mentioned inside this documentation here inside the button we will show this start so this is how the login form looks like now let's fix everything in proper place but that first of all we will wrap this form with this material ui component box it is similar to add diff now in order to customize any material ui component you can use this property sx for that you can go to the uh corresponding api documentation for button here we have the corresponding link so here we have the available properties for the component and here you could see the sx it will accept these types of data and here this sx page tells how you can customize the component by passing an object like this okay so here we go s6 first of all we want to pass an object for that first of all we have to wrap everything with a pair of curly brackets like this since we have to pass an object we need another pair of curly brackets like this now here we are going to customize these input text boxes here now if you inspect these text boxes you could see that for any media ui component there will be a root css class like this you can use the corresponding class for customizing this specific component and the root css class for this text field component is mui form control hyphen root to see the same let's search for the corresponding api text field api inside this documentation at the end you could see the root css class as mui text field root so in order to customize text field you can make use of this class here now how this customization is done for that let me copy this css root class here you could see the same root class applied to this root outermost div for this component text field here the text field from mui displayed with an html div and the outermost div is having the root class specified inside this documentation here now in order to customize this text field we'll be using the same class like this so first of all i'm pasting the class here now this class is applied to a child component text field when considered to this box component here this is a child component for this box component here so in order to specify that we could do this now this and simple represent this box component itself now when you specify a class with a space in between them it means we are going to apply this css when this class comes as a chart right this is same in css also so this is how we do it whatever styles that we specify here will be applied to the children of this box having this class so first of all i want to specify a margin of the range 1. as per the sx abbreviation you can shorten this like m like this now you can see the margin is applied to this text field now in order to split these text field into multiple lines i will add this with attribute here 90 percentage see both of them are displayed on separate lines so this is how we are going to customize material ui components from now onwards now we need a separate line for this submit button also so i will add this sx attribute we want to apply the styles to this component itself so we can directly pass the style here with is equal to 90 days now i want to show this component inside a medial ui component card so let's search for card here here we have various samples showing how you can make use of this component now let's quickly add the element inside this application here now with what we have explained now you can easily follow and understand the dli components that i'm going to use inside this application if you have any doubt you can go through this documentation here now let's quickly complete this design here first of all we need a card component the content of the card will be displayed inside this component card content so let's move this form into this code content now let's set the width to 400 pixel now before anything as i want to center this card component here for that i'm going to create a new component called center center.js and here we have the snippet to create the component now in order to center anything i'm going to make use of material ui component grid so here we have the component grid it is similar to the bootstrap 12 grid system first of all we have this component grid which is the container so we have to specify that with this attribute container and inside that we need same component grid marked as item so this is the container for the grid and this is similar to a column and the width of this column is specified with this attribute s6 and i will set it as to one column space now in order to align anything inside this grid at center we could do this direction is equal to column and then set align items and justify content as sender and finally we have to set the mean height so i will use this property sx mean height i will set it as 100bh now we just need to wrap everything inside this login component with this center component here whatever we have wrapped with this center can be accessed with the props parameter here and it will be the inside this property props children let's check that here sorry we have a type o inside the center component i always makes this mistake instead of this equal simple we need a colon boom that's it now finally we need an h3 header for this login form here so i will add this typography component we need an h3 header so i will set this gradient as h3 and we need some vertical margin so i will do this margin on y-axis of the range three inside that will show this quiz app now here we have everything we need we just need to align them properly but then i will add this our css style here text align as sender now there is one thing that i am recently concerned about which is dark themes these live themes cause a lot of eye strains compared to dark themes so i'm gonna quickly switch into dark theme with material ui so you can search for the documentation here we just need to customize the default theme so open this a root javascript file index.js if you want to stick with the light theme you can ignore these steps here so first of all we need a theme object and here we will call the material ui function create theme now we have to pass the object with our customization we just need to change the mode to dark so let me copy this object from here and let's paste that over here now we'll wrap this app component with this theme provider now here we just need to pass the theme that we have just created now finally in order to work this we need to add one more component the asus baseline boom that's it this is more healthy for your eyes in long term now here we have done with the design in a bit we are going to create dotnet cover bbi to store these email and name here before that i just want to validate the form here let me close all of the component except this login component now first for we want to manage the values of this text field inside the state of this component right for that we normally test this we'll be creating state object like this value then set value and then we'll be initializing it with use state function inside this we will be passing an object with the initial values instead of this i will be creating a separate folder called hooks inside that i will be creating this uh hook component used for we have done this same multiple times in previous tutorials i will just paste that same here and let's explain it so here we have a component inside this hook we have two state objects values and errors inside these values state object we'll be saving the values from these text field here and the corresponding text field errors will be saved inside this object this rs object is initialized with the empty object and this values object will be initialized with an object returned from this function this function will be passed as a parameter to this hook we can see that in a bit and here we have the handle input change we don't have to rewrite that in all of the components where we have f4 and finally we'll be returning everything that is required for the component with the phone so let me get rid of this now we could do this now we can call the use form hook here now this hook returns an object with these properties now we can restructure the same inside this component here now in order to initialize this state object values we have to pass this function get fresh model object so i'll create the function here get press model this is just a function to retain an object like this so here we go name and email address with the default values is passed now we just need to pass the same inside this hook here now we can assign values from this object to these text field here values dot email the name of the component and the property used inside this state object must be same that's how this hook is created you could see that inside this handle input change here okay i hope you don't need an explanation for this handle input change even method here most of you know how to handle this input change for these uh text fields here now we can provide the on change even function which is already defined inside the hook until input change okay that's it now let me copy this and pasting for name so here we have assigned value for this text field if you want to verify whether it is working properly or not i will add this submit event login so here is the function login with the default parameter e first of all we have to prevent the default behavior of the form which is reloading the form so prevent default now let's print the state object values now here we have the dev console let's enter some random values and submit the form boom that's it so the values from these input text fields are saving into our state object values now finally i want to implement validation inside these form controls that i will be creating a separate function validate first of all we'll be creating an object empty object like this then we'll be saving the errors related to email with this property email now in order to validate email addresses i'll be using this regular expression now we just need to call this test function into that we can pass the values from our state email if email is in proper format then it will return true so we don't have any error message otherwise we will say email is not valid now like this we have to have the uh name validation so values dot name is not equal to empty string then we don't have an error message else we will show this field is required finally we will set these validation error messages into this state object errors return from this scope here so set errors into that we can pass this temp object and finally from this function we need to return a boolean value indicating whether this form as a whole is valid or not for that all of these error messages here should be empty string right but that we can make use of this object method values inside that we can pass this temp object so actually this function returns an array of values inside this object here and on that return array we want to call this array method every and inside this we want to check all of the values inside this object are empty string so if all of them are empty string this will retain true otherwise pause so that indicate whether this form as a whole is valid or not so inside this submit event here we can call the function validate so this log statement works if the form as a whole is valid and finally if any of these text field is invalid you want to show them inside these corresponding text field here in order to do so in material ui first of all we have to set this up property error as true and the validation error message will be shown with this property helper text now we want to do this dynamically if this field is invalid for conditionally applying those properties first of all we wrap everything with a pair of curly brackets like this and then i will do the d structures index like this inside the state object errors if the value of the property email is empty or not if it is not empty we want to retain an object with corresponding properties like error set as true and then the helper text which is errors dot email if there is a validation error inside this property email this object will be returned from the statement and it will be restructured here and thereby the properties inside this object can be a part of this outer component here so this is how we dynamically apply properties in react components now let me copy this and pasting for name text field now let me save this and back to the application here let's check whether it is working or not let's try to submit the form here let's provide an invalid email pass some random name so validation is working for name now let's make this valid boom it's working properly fine now it's time to create an asp.net cover baby i project to save these informations from these fields and to process other queries related to quiz application for this project i'm using visual studio 2022 and the latest.net conversion 6. now let's start with creating the dot net core web api project i will select this template asp.net core web api name of the application quiz api select the location where you want to save this project so i am selecting this project folder where we have already created our react application as i mentioned already make sure to remove special characters from this folder path directory here so select the folder now let's create the project here i'm selecting the latest dotnet course 6 version i will uncheck this configuration for https since we are creating this application for development make sure to enable this open api support it is really helpful to test the api now let's create the project so here we have the brand new asp.net core web api project first of all let's start with db model and db creation using entity framework for that first of all we have to install corresponding npm packages so right click on this project here then manage and you get packages inside this browse tab search for entity framework let's download this our microsoft entity framework core now from this version drop down here select the same version as that of the framework here so six or two so selected the same version here now let's install the package accept the license now along with the package we need to install these two packages sql server and tools select the same version as that of the framework click on install entity framework called tools so here we have done with the installation of these three entity framework packages now let's create model classes for the db so first of all i'll be creating the folder models so first of all we have question model first of all we have this primary key question id now the column corresponding to this property will be the primary key for this table so we have to mark this with this key attribute now we have to import the corresponding namespace for that you can use this uh shortcut hold ctrl then press period and select this namespace here data annotations then we have the actual question question in words then image name the name of the image required for illustrating this question will be saved inside this api and will be shown along with the question so the image name will be stored inside this column and the actual image will be stored inside the project directory here then we have the four options for this question finally the answer for this question which is the index of the option from these options here since image name is optional i want to make this property as nullable but that we just need to add this question mark as a suffix to this data type string here now if we leave these model string properties as it is when it is converted to the actual db the sequence server columns corresponding to these properties will be having the data type of n vocab max which is more than what we need so in order to limit the data type we will specify the required data type here so first of all we have this attribute colon import the namespace here now with this type name we can specify the data type as n work 250 so this is offset type 50 and work f50 sorry i made a mistake all of these options are off the type string so let me correct that here and all of them will take the type and work at 50. now like this let's create one more model for the participant first of all we have participant id then email name of the participant score time taken to complete the quiz let's mark this property as the primary key now let's specify the column type for the string properties so let me copy this let's add the corresponding namespace so that's all we need as model classes now let's create the db context quiz db context now we have to inherit this from the entity framework class dbcontext now let's use the corresponding namespace entity framework core now we have to specify the constructor for this class and this constructor will have a parameter of the type tbcontext options of the type quiz db context as options and we want to pass the same parameter to the base constructor now we'll be creating the db and the tables corresponding to these model classes using migration in order to do so inside this db context clause here we have to have a reference to those particular modal clauses here for that i will be creating properties of the type db set with those modal clauses now in order to use this quizdb context by the framework we have to inject this db context instance into the framework with that open this program.csv file in previous version.net 5 we have been doing this in a file called startup.cs but in dotnet6 we'll do the dependency injection inside program.cs now for the dependency injection we'll be using this builder instance here builder dot services dot add db context of the type which db context as an argument to this method we'll be passing a lambda expression with this options and here we have to provide the provider for this uh db meaning we are going to specify which database we are going to use for this application it will be sql server so we can call this method here use sql server now let's use the corresponding namespace now into this function we have to pass the connection stream so first of all let's save the connection string inside this app settings.json file here so here we go connection string and inside this i will save the connection string with this name dev connection and now for the sake of explanation let me paste the template for db connection string here so first of all we have to provide the sql server instance name in my case it is local sql express so here i'm using a sql express instance that is installed on my local machine and here we have to provide the adb name so quiz db so there will be adb created with this name quiz db for this connection we'll be using windows authentication so set this trusted connection as true and finally in order to execute multiple queries at a time we have set this property multiple active result sets as true now before going further first of all check whether this instance is already started or not for that first of all open your run a window for that you can use the shortcut windows logo key then r it will open up this run command here and then just type services.msc it will open a window containing all of the services installed on your system so let's search for the sql server instance here so here we have the sql server instance name sql express so you have to use the same name inside this uh portion here and make sure that this sql server service is already running inside your machine if not you can see a start option here now let me close this services here so here we have a proper connection string save this back to this dependency injection here now in order to retrieve the connection string saved inside this json file here we just need to do this builder configuration dot get connection string here we just need to provide the connection name that we have used here so it is div connection so here we have done with the dependency injection now let's build this project after successful build we are going for migration which is the process of creating the actual physical db with these model classes provided here for that first of all select the project then go to choose then manage a new get packages then package manager console and make sure the same project that we have here quiz api is selected from this drop down now first of all we have to execute this command add migration i will name this migration as initial create hit enter during this process the actual sql server script will be created according to the model that we have inside this project which is saved inside this new folder migrations now in order to execute the sql script for creating the db we have to execute this command update database you could actually see the sql script inside this a package manager console window itself now once it is done let's check whether it is created or not for that i will open my management studio here now let's connect to the same server instance that we have specified in the connection string so here we successfully made a connection to the sql server instance now let's expand this databases note here boom that's it so here we have the new db with the name quiz db the name of this db is already mentioned inside this connection string here now let's check whether those tables are created as per our model clause so here we have those two tables participants and questions now make sure that these tables are created as per the model clauses that we have provided here the name of these tables questions and participant is taken from this db context property db set now i have prepared 10 questions for this quiz app so let's execute the query here for now i will paste in session query here i have given this sql script inside the github repository let's execute this so here we have installed those 10 questions let's check that inside this table here so here we have the 10 questions that i have prepared the actual question is here inside this column if there is an image for this question the corresponding image name will be saved inside this column here then four options and inside this answer column here the correct option index is saved inside this column for option one the index will be zero then one two three like that like the array index now enough with the db now let's add this image mouse.png inside this project directory here for that i'll be creating a new folder images now here is the image let me move this to the new folder here now it's time to create api controllers for these model classes with that first of all let's build this project after successful build right click on controllers then add controller from this left panel select api then api controller with actions using entity framework model clause will be question context is question db context question controller so here we have successfully created the api controller because of scaffolding mechanism required web methods are already added to this controller here now there is a common error while creating controllers with this scaffolding mechanism which is related to installing code generation design package so let's check that here right click on the project then go to manage and you get packages and let's search for the package here code generation design so here is the package it is already installed in this project if you have an error message related to code generation package if the packet is not installed here install the package with the same version as that of the asp.net core if it is installed and you have the same problem then uninstall the package and install it again okay so in most of the case that will solve the problem now back to this controller here now let's create one more controller for this model participant participant controller now that's also done now let's focus on this controller here for any created controller inside the controller constructor you could see a parameter of the tab with db context now from both the value for this context parameter is passed that's where dependency injection comes so whenever there is a constructor parameter of the type quiz db context the instance for that will be passed from this dependency injection here so that's how dependency injection works an instance of this controller is created whenever we make a request to these web methods here then the framework automatically create an instance of this controller since we have a constructor parameter of the type quiz db context the dependency injection will provide the db context and it is saved to this private parameter underscore context and inside these web methods here we underscore context is used to feed or query the database that we have created at this moment we want to feed the participant email and name to this wbbi here for now let me collapse these methods here and for saving the participant details i will be using this post method here so this existing post web api method will insert new participants but we want some customization here we will insert the corresponding participant details to the corresponding table but if the combination of name and email is already existing we won't insert it instead of creating a new participant we will be returning the existing participant details back to the client side so first of all i'll be creating a temporary object here now let's check whether we have a participant with given name and email address participant and we can call this verb method and here we have the lambda expression x such that x dot name is equal to participant name and let's compare the email also and finally we have to call this method post or default if there is no such participant we will do the insert operation like this here else we will assign the temporary participant to this participant variable and finally from this method we will return the object participant okay now let's run this application now by default the asp.net cover bp i will open an interface to interact with the api that we have created all of the web methods are here you can test them with these interface here we'll be testing some of the web api methods here now from this login form here we have to submit the email and name so back to the vs code here here we have the login form submit event now in order to make an api request from this react application to the web api method here we need to install the package axios so let's do that here i'll open new terminal and let's do this npm install axios now in order to handle api requests i'm going to create a separate folder api so that we will create this index.js first of all let's import the axios package here now let's create and export this constant base url inside that i will save this base address here so let me copy this okay that's it now i will paste this function here i have been using this pattern in almost all of my react to do this before we have a function create api endpoint and which is exported from this index.js for this function we have an endpoint and here we have generated the complete url and from this function we have returned an object with functions required for all of the operations to retrieve all of your requests we have this fetch function to retrieve a specific record with a given id we have this function here in both of these case we are making a get request with the corresponding url and with this function we are inserting a new record and here we have the put method to update an existing record and this delete function delete an existing record so these methods get paused put delete methods are from axios and they will make a get request these corresponding web api methods of the type post get etc you will understand this better as we go forward so inside this form submit event we have to make a post request to this controller web api method here for that we could do this first of all we will call the method that we have just created into this function we have to pass the endpoint for the url so the base url is already created base url with the api and we just need to append this up controller name here participant so that's the default route in an api controller which is already mentioned at the top here api forward slash name of the controller in this case participant is the controller name so api 4 slash participant now we just need to pass participant here in order to avoid typo here i will be creating a constant object here endpoints it's an object and here we will do this participant i will save the same inside this property and let's export this constant now we just need to do this endpoints participant now this will retain a collection of objects like this in order to make a post request we can call this function post into this function we just need to pass the object that we want to insert the url is already generated up above here so we'll pass this state object values which contains the feed values here now we can handle the response inside this then function here so here we have we call back with the response for now let's print this response in developer console response if there is any error we can handle that inside this callback here now let's save this and back to the application now let's submit this form for creating a new participant now let's submit the form here we have an error so here is the problem there is a security feature in almost all web api project called cross origin resource sharing meaning this web api will block requests from another application which is hosted on a different domain or a different port number like this case here we have different port number so this will be i will block request from the port number 3000 here so first of all we have to enable course for this port number here back to the web api here and let's stop this execution now once again open this program.cs file now let's enable course we can make use of this method use course from this app object here and here we have the lambda expression with options options dot with origins inside that we have to pass the corresponding origin so let me copy paste that from this react application here make sure to remove the forward slash at the end and finally we have to call these two methods allow any method and allow any header now let's run this application without debugging now back to the react application let's clear these existing errors here let's submit this form again boom here we have the response from the post web api method and this property data is having the response that we have sent from this post baby method here now let's check the participant table that's it so here we have the new participant john smith now in order to check whether it creates a duplicate participant let's reload this page and let's try to make the same participant again in order to make it easy i will enable this option for autocomplete so let's set this as on here save between the application reload this time it's not working because previously the autocomplete was off in future the previously posted data will be shown as an auto suggestion here now i will just copy the details from this table here submit the form we got the response with the same data from this participant id itself we could say there is no new participant the accessing participant must be returned see that's it so login is working perfectly fine now what else now from now on was the real game begins now we need a state management mechanism to store oppressive and share the data inside the application across various components inside the application in previous react applications we were using redex but for this application we'll be using context api so let's integrate context api into this react application here first of all let's create rest of the main components inside the application after login we'll be showing this component here question now here we have the final component for showing the result of this quiz program now let's look how to preserve the state of this application and how to share common data among these components for that i will be creating a new hook here use state context first of all we need a react component so here it is and let's name this as context provider now let's create a context object state context now we just need to call this function create context so the nice thing about this context api that everything is already though inside the react library itself now let's add the corresponding import statement so for this component here we have the default parameter props now we will be wrapping everything within this context provider where we need the data from the context api so whatever we have wrapped with this provider can be accessed with the children property here now from this component we are wrapping everything with the context provider like this state context dot provider and we'll be showing the children here now for this component we'll be creating a state object like this context and set context and let's call this function use state so inside this context object we'll be saving the data that we want to share across these components here now in order to initialize this context object i will be creating a separate function get fresh context from here we will return an object with properties that we want to save inside the context with their default values so first of all we have participant id initialized with zero then time taken to complete the quiz selected options array so these are the data that we want to share globally across this application if you find anything additional you can add them here now let's call this function here now we will pass this as a value to this context api here context and the corresponding set context function so the data of this context is saved inside this component state object context and it is shared across the children of the context provider here so here we have created and exported this context provider actually we don't want to export it as default so let me remove this from here now let's wrap everything within this context provider now let's open the index true javascript file context provider now this app component and its children components can access the data from this context provider here let's check how it is done so first of all we have to export this context object here now let's try to access the values from this context inside this question component here first of all we have to call this function use context inside that we can pass the state context object that we have created well let's add the corresponding import statement now this function will retain an object we can restructure the same here the return object will be similar to the object that we have passed here it will contain this context and set context so so while restructuring we can use the same property name so let me copy this and pasting here now this context object contains the values from context api and this set function can be used to update values inside the context here so it is exactly similar to handling a react component state object the only difference is that here we have a context provider and this provider uses to wrap every component inside the application and that's how this context is made available across the children components in order to update the values inside the context api we can do the same thing that we do with a component state object we will restructure whatever we have inside the context now if you want to update the time taken for this quiz program we can just update that property here so this is how context api works now we want to make these steps even more simple because here we have imported the use context function and the context api object and everything is restricted here in order to update the values we need another destructuring here so i would like to show you a best practice that you can reuse in your applications for that we'll be creating a hook here called use state context and let's export this same by default now inside the hook we will destructure everything inside the context api so let me copy paste this now from this hook we will be returning the d structured context and the corresponding set function now we don't need to import the state context object and this use context function here we just need to call the hook that we have just created use state context now i want to even simplify this set context function here just to avoid this destructuring here for that i will redefine this set context function here so here we have the function for this function we expect a parameter object and this object contains the properties inside the context with the updated values okay now inside the function we'll be calling the original set context function inside that first therefore we will restructure the context object and then we will destroy the object parameter so the redefinition of the setcontext function is only though inside this return object inside the child component we don't have to restructure the context object again we just need to pass an object like this it will be restructured inside this redefine function here hope you will find this more efficient so this is how we are going to use context api inside the application let me remove these statements from here now let me remove this set context function invocation here now back to the login form let me try to login with the same details that we have provided previously so after successful login we have to save this a participant id inside our context api for that let's call this use state context hook that we have created here context and set context let's call the hook use state context now inside this success callback we just need to update the corresponding participant id so we'll call this function set context inside that we just need to pass an object with the updated participant id so the return data from the server can be accessed with this property data inside that we have this property participant id now if you want to check the values inside the contacts api let's print the same here context now let's try to login with the previous participant submit before sorry here we have an error set context is not a function so let's start with the context provider itself we have created the state object context and it's set function and we have passed the same here this pair of curly brackets indicate that we have something from javascript since we have to pass this context object and this set function we have to pass them inside an object like this then only it will work as we expected okay so an object with the context object and its set function is passed to the context provider here let me save this and back to the application let's try to login with the previous participant let's check the console window here we have printed the values from the context api and it is showing the initial value itself not the updated participant id because this set context function is asynchronous immediately after invoking this function this function get executed since this function is an asynchronous function it is running in the background and this function will get executed even before updating the value here so if you want to see the context value i will do something else inside this render method we can print the context value participant id reload the app initially you could see that its value is zero now let's try to log in with the same participant boom that's it the value of the participant id inside the context is getting updated now after this login operation here we want to show the quiz component but we are planning to show the questions from our db for that first of inside this application i'm going to rename this component as quiz component let's update the name here also now currently inside the default app component app.js we are showing the login component instead of that we need a simple routing configuration inside the application for that first of all we have to install this npm package react router dom so here we have successfully installed the package if you are new to react router don't worry this application is perfect for you to understand how react router works now let's get rid of this login component first of all we need to wrap everything with this component browser router and we have one more container routes now we can specify the routes for this application so first of all we have the default route for the login component for the default component path will be a forward slash with this element property we can specify the component that we want to show inside this route which is login now let me duplicate this for rest of the two components quiz and result so here we will be showing the quiz component and here we have the result component sorry we forgot to import routes and route hope you know the shortcut for possible imports hold control then press space now let's do the same for this route reload the application so by default the login component will be navigated with this default route here okay now after the successful login we have to navigate inside this route forward slash quiz in order to navigate into the quiz route first of all we have to call the use navigate hook so we could do this navigate is equal to use navigate now inside this successful callback we just need to call the function navigate with the corresponding route forward slash quiz before trying this let me print this participant id inside this quiz component here so we have already restructured the context now let's print the context value inside the dev console context that's it let's login with the previous participant boom so here we have successfully logged in inside the application and here we have the quiz component now here we have the current value from the context api now there is one thing that you must know about context api the values inside the context api will be lost once you reload the application like this here see the participant id is reset to its initial value so how can we preserve the context api value across the application that will be discussed in next video so in remaining tutorials we have to fetch random five questions from the api and displaying that in our react component here after completing the five questions we have to show the result of the quiz program along with the correct answers for the question attended by the participant once we complete this project i'll be sharing the github repository link in video description for more react or asp.net core tutorial please consider subscribing to the channel if you haven't yet please like and share this video see you in second part
Info
Channel: CodAffection
Views: 76,228
Rating: undefined out of 5
Keywords: react quiz app, react projects, .net core web api, react game, react project for beginners, react and asp.net core api, react quiz app with timer, asp.net core web api quiz, material ui quiz app, real world project with react material ui, quiz app, build sample project with react.js and asp.net core, latest material ui, material ui v5
Id: MV1rEWlcW7U
Channel Id: undefined
Length: 53min 26sec (3206 seconds)
Published: Tue Mar 08 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.