React with .NET Web API – Basic App Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this course you will learn how to integrate a react application with a.net API component Gavin Lon teaches this course Gavin is a freako camp team member and one of the creators of our popular full react course hi and welcome I'm Gavin long in this video we are going to build a basic react front end that queries a web API component written in C sharp so by going through this video you'll learn one of the easiest ways to create a react application that leverages a.net web API component we'll code this application using visual studio 2022 Community Edition which can be downloaded free of charge I've included a link in the description of this video that points to where you are able to download visual studio 2022 Community Edition for both Windows and Mac OS platforms the function of this basic application enables users to rank items by dragging and dropping the relevant items for example well-known movies onto a grid each cell in the ranking grid denotes a ranking value so basically the item that has been dragged to the top left ranking cell is ranked number one the item to the immediate right of the top left ranking cell denotes a ranking value of two and so on the worst possible ranking is 16. denoted by the cell in the bottom right cell of the ranking grid this is of course not an original app but I thought this would be a great way to demonstrate writing a basic react front end that leverages a web API component that runs on.net 6. okay so as you can see I got myself a green screen the only problem that I can think of about having a green screen is that you run the risk of getting carried away okay so I'm glad I got that out of my system let's get into this video let's fire up visual studio 2022 the project template that we want to use for this project is named asp.net core with react.js so let's select this item and press the next button let's name our project ranking app let's press the next button as you can see we are going to build the.net part of this application on.net 6. let's press the create button great let's take a brief look at the project structure that has been automatically generated for US based on the project template that we have chosen to access the client-side code we can open the client app folder here then we can look at the react components that have been automatically generated within the SRC slash components folder we have the counter component the fetch data component and the home component then to look at the auto-generated service site.net code we can open the controllers folder here we have the weather forecast controller class which contains code for a.net web API component if we look here we have the get action method that represents the get verb pertaining to a HTTP get request this method returns an array containing made-up weather forecast related data this code has been generated for us through the use of the relevant project template to give us an example of how the interaction between the front-end react code and the.net backend web API code can be implemented in our project the react client component named fetch data calls the weather forecast.net web API component and displays the weather forecast data returned from the get request to the browser the counter component demonstrates basic react functionality but when we click the fetch data menu option the code within the fetch data react component is invoked and calls the weather forecast server-side.net web API component and displays the data that is returned as an array to the client on the user's browser you can see that the asp.net core with react.js project template automatically generates code for us to facilitate the integration of a.net web API component with the client-side code implemented using react.js so let's create a folder here named models let's add a c-sharp class to the models folder and let's name our class item model in this video we are going to develop a basic application that enables a user to rank movies and albums we'll first create the code whereby a user can use our application to rank a collection of movies but we want our model class to be generic so the item model class can also be used to represent for example albums or other types of items we want users to be able to rank using our application so the item model class can represent any type of item that we may wish to integrate into our application so this helps our application to be extensible let's include an ID Auto implemented property of type integer let's include a string property named title let's include an integer property named image ID each item will have an Associated image our application will contain a collection of images that are uniquely identifiable so each item will be associated with one specific image an item has a one-to-one relationship with an image in the system you'll clearly see how this works as we progress with the creation of this application let's include an integer property named ranking this property represents the ranking value that a user can assign to a particular item let's include an item type property of type integer in this application we are going to allow for the user to rank a collection of movies as well as albums so we are going to assign movies the item type identifier value of one and albums the item type identifier value of 2. so item types have a one-to-many relationship with the items in our system this will be clarified as we progress with the development of the application so let's create our controller class within the controllers folder let's add a class and name it item controller this class will contain an action method that will service HTTP get requests from clients when a valid request is made to the relevant get action method the action method will query a collection of items and return an array of items for a specific item type to the appropriate react client component so for example if a client requests an array of items that have an item type of one an array of items representative of movies will be returned to the client so to make our class a controller class let's first make our item control across inherit from the controller Base Class let's press Ctrl period and bring in the microsoft.asp.netcore.mvc namespace the next step in making our class controller class is to decorate the item controller class with the API controller attribute in order to declare appropriate routing information for our controller class let's appropriately decorate our item controller class with the root attribute let's pass in the text controller wrapped in square brackets as an argument to the Constructor of the root attribute so I want to keep the server-side web API component code really basic because the focus of this tutorial is how to easily Implement interaction functionality between a react client and server-side web API code implemented using.net so for the sake of this basic example we are going to implement the data on the server side as a static collection rather than for example storing the relevant data in a SQL Server database in a database table if this was a real world application of course we'd want to persist the relevant data and for example a relational database storage facility black SQL server or perhaps a nosql storage facility like mongodb we could then use for example Entity framework core to interact with whichever storage facility we have chosen So within our item controller class let's create a private static read-only Eye enumerable collection that is strongly typed with our user-defined type item model let's name our collection items note that rather than follow me here tapping away at the keyboard to declare and populate our items collection you can copy the relevant code from this URL that points to an appropriate GitHub webpage so you can see here we have in our collection references to well-known movies The Godfather Highlander Highlander 2 The Last of the Mohicans Police Academy 6. rear window Road House the Shawshank Redemption Star Trek 4 the return home and Superman 4. so this get action method accepts an argument of type integer named item type let's create a link query that queries our collection of items in order to filter the items collection based on the item type value passed in from the code that we'll write a bit later within a react component note that at the moment the items in our collection denote movies so only one type of item is currently stored within our collection later on we'll extend our code whereby albums will be stored within this collection so in order to tell.net as it were that this get method pertains to a HTTP get request we must decorate our get action method with the HTTP get attribute we must also pass in this text denoting that an argument of type int must be passed as an argument when the relevant get request is made from the client let's create a react component let's name this file rankitems.js for those of you who wish to learn the basics of react or wish to refresh your knowledge I've recently contributed to a project-based react for beginners course for freecodecamp.org I've included a link to this course Below in the description of this video I'm really happy to have contributed to this course along with two other instructors John smilga and sanjif Theo garajan John and Sanjeev are both excellent instructors and very well known I've included links to their YouTube channels Below in the description of this video let's write the code to import the use statehook and the use effect hook into our rank items component let's create a basic structure for our functional component let's write the code to return some basic jsx code from our component let's write code to implement the use State hook so that react can track the state of the items collection returned from the server through the code that we have just implemented for our item controller class so you can see here we have a destructured array returned from the use statehook the first variable returned pertains to the items collection data that will be initially retrieved from our server-side code and the second variable pertains to a function that can be used in our react component to change the state of the item's variable we'll appropriately implement the code to change the state of the items array in just a bit note that at the moment we are setting the items array to an empty array by default this is denoted by the empty square brackets we are currently passing in as an argument to the use State hook here so when our rank items component first loads we want our codes to call the appropriate web API component in order to retrieve the relevant items collection data from the server and then we want our code to change the state of the items array we are able to implement code that executes when our component first loads by using the use effect hook in a specific way to achieve this we need to pass a function as the first arguments to the use effect hook and pass empty square brackets denoting an empty array as the second argument to the use effect hook let's write code for an anonymous function that we are passing as an arguments to the first parameter of the use effect hook so we want our code to return a collection of movie data from our web API component we can use javascript's fetch method to make an appropriate HTTP get request to the relevant endpoint we need to pass a value denoting the item type value to the server in the rules of our application a value of 1 for the item type argument means we want to return a collection containing data for movies a value of 2 for the item type argument means that we want the collection to contain data for a collection of albums we haven't yet added the data to our server-side code for the collection of albums but we'll start by testing the code for retrieving a collection of movie data so the data type variable on the client has been initialized to one which means the relevant web API server-side code should return a collection of items with an item type of one movie data the data is returned in Json format if our code gets to this point and a valid collection of movie data has been successfully returned from our web API component we can use the set items function to change the state of our items variable when a variable status tracked through the use of the use statehook and its status changed this means that the state of the component has changed when the state of a react component changes the react component is re-rendered so the code within the returned jsx code is transpiled into code that a web browser understands before it is re-rendered inside the user's browser window the code is appropriately re-rendered really fast which is what makes react such a great choice for implementing user interactive front-end code for the web so we have now created basic code for our rank items component that retrieves appropriate data from the server then changes the state of our component which results in our component being appropriately re-rendered the next step is to appropriately modify the app root.js file let's open the approots.js file let's modify the app Roots array in order to add a new route that points to our rank items component as it were we must of course also write code to import the rank items component into our approot component great so we have told react as it were about how to access the rank items component through the code that we have just written within the app Roots component the next step is to include the relevant link within the nav menu component to provide a way for the user to navigate to the rank items component as it were let's open the file named navmenu.js let's appropriately include a nav item element and include a nav link child element within the nav item parent element let's ensure that the path that we have appropriately included for the rank items component within the app Roots array is appropriately included within our new nav link element we can do this by appropriately assigning the relevant path to the rank items component to the two property of the nav link element let's run our code and test whether we can invoke the rank items component by clicking the appropriate navigation link that we have just created okay so why has that not worked by using the asp.net core with react.js project template to create our project code has been automatically included within our project to make the interaction between the react client code and the server-side.net code easy for us to implement so all we need to do is tell our client react code as it were about our server-side controller class and we can do this by simply including a reference to item our item controller class in the context array like this you can see here by default the context array includes an item denoting the weather forecast controller class that is used by the fetch data react component to retrieve weather forecast data from the server that can then be rendered through the fetch data component so we can include a new entry into the context array that tells our client-side code as it were about the items controller code on the server let's run the code and you can see that our break point has been hit within the get action method within the item controller class excellent our rank items react component is now successfully communicating as it were with the appropriate server-side web API code and each movie title is rendered to the screen when our rank items component is re-rendered after the movie data is successfully retrieved from the server and the set items client-side function is called to appropriately update the items array with the movie data retrieved from the server this of course changes the state of the rank items component and the relevant front-end code is appropriately re-rendered to the browser excellent so if our code was retrieving a large amount of data from the server it would be a good idea to show a loading indicator to the user while the data is being delivered from the server to the client providing such status information to the user provides a better ux user experience so to simulate that a large amount of data is being sent from server to client let's create an artificial delay on the server like this so you can see here that an empty array is currently set by default in the relevant use State hook so of course the array will never be null so in the return code here instead of checking for a null value let's check the number of items in the array so while the array is empty I.E has not yet been brought down from the server we want a loading indicator to be displayed to the user great so instead of just displaying the movie titles to the user's browser we want the poster images for each of the movies to be displayed in a list to do this let's first create a new react component that has the responsibility of importing Movie images into our application let's name the relevant react component with the images.js before we write the code for this component let's create a folder within the SRC folder named images I've prepared the movie images for our application and they can be downloaded from this location on GitHub so let's create a folder within the images folder named movies and let's ensure that the images that we have downloaded from the relevant GitHub repository resides within this movies folder let's write the code to import the images from the movies folder we can do this by including the appropriate import statements at the top of our movie images.js react component like this if you like this video please give this video a thumbs up and please feel free to share this video with anyone you feel May benefit from its content please also consider subscribing to the channel and hit the Bell icon so that you'll be notified of future content let's create an array to store these imported images then let's write the code to export our array so that other components can use the array within the div element that will wrap the list of movie images that we want displayed from within the rank items component let's reference a CSS class that we'll write in just a bit named items Dash not Dash ranked then let's write the jsx code to Output each of the images to the screen from within our rank items component note that each item that our code traverses has a property named image ID which corresponds to an ID property of an object stored in the movie image error array let's write code that uses the JavaScript find method to find the appropriate image for each item great but the images are of course too big so we must style our images appropriately let's first create a div container element for each of the relevant image elements let's include a reference to our CSS class for each of our div container elements let's call our CSS class unranked-cell let's open the custom.css file and create the appropriate styling code so firstly let's create the appropriate CSS code for the items Dash not Dash ranked class let's then create the appropriate CSS code for the unranked Dash cell clause and let's also create the appropriate CSS code for the IMG elements that are housed within the div container elements that reference the unranked Dash cell CSS class excellent and we are now presented with a list of movie images each of these images denotes an unranked movie item so we have now created the functionality for displaying the movies we want our users to rank in a list so the way in which we want our users to rank the items is by dragging the relevant images onto a grid the position to where the user drags an image will result in a unique ranking value that corresponds to each cell within the ranking grid being allocated to the relevant item I.E the dragged image item which represents a movie so for example when a user drags the image representing the movie The Godfather to the top left position in the grid the ranking grid this means that the item is ranked number one so the item's ranking value is one so each cell in the ranking grid denotes a ranking value except for the cells in the leftmost column these cells are used for labeling purposes so each cell in the ranking grid denotes a ranking value the ranking value is positioned for each ranking cell progressing from left to right and top to bottom by a value of 1 from 1 to 16. so the top left item denotes a ranking value of one the item to the immediate right of the cell that denotes a ranking value of one denotes a value of 2 and the bottom right item denotes a ranking value of 16. so our UI will give the user a great ux where the user can simply drag the image representing an unranked item to the chosen position on the ranking Grid in order to allocate an appropriate ranking value to the relevant item a ranking value of 1 denotes the most highly ranked item and a ranking value of 16 denotes the lowest possible ranking value great so let's create a react component responsible for outputting a grid to the screen that will denote our ranking grid let's create a component named ranking grid.js let's first create the basic structure for a react functional component so we are using de-structuring here for the props that the rank items component will pass down to our ranking grid component the rank items component is the parent component of the ranking grid child component so here the items array and the image array are passed down as props to our ranking grid component so we are going to create the code for the Grid in this component dynamically through appropriately coded JavaScript methods what I mean by this will become clearer as we develop the code for this component so firstly let's declare five JavaScript arrays these arrays will be used to build relevant jsx code that can be outputted from our component the ranking grid array will store an array of elements that make up the entire ranking grid the cell collection top array will store the elements that represent the top row in the ranking grid the cell collection middle array will store the elements that represent the middle row in the ranking grid the cell collection bottom array will store the elements that represent the second most bottom row in the ranking grid the cell collection worst array will store the elements that represent the very bottom where all the worst ranked items will reside as it were after being ranked by the user let's create the code to return the relevant jsx code let's write codes to call a JavaScript method named create ranking grid that is responsible for outputting the jsx code for our ranking grid in the create ranking grid method a call to a method that we have not yet written is made named create cells for rows this code is returning the returned value from a method that we'll write next named create rows for grid so let's work backwards as it were and create the code for the create rows for grid method so you can see that this code simply pushes jsx elements into a JavaScript array the first item in the array represents the top row for the ranking grid the second item in the array represents the middle row in the ranking grid the third item in the array represents the second to bottom row in the ranking grid the fourth item in the array represents the very bottom row and the ranking grid let's create the code for the method named create cells for rows so here our code is looping four times IE one for each row in the ranking grid within the loop a call to a method named create cells for row is made this method is responsible for creating each cell for a particular row let's create the code for the create cells for row method so each row will contain five cells so let's create code to Loop five times each iteration of the loop creates a cell for the relevant row the first cell in each row does not have a corresponding ranking value and is used to label the relevant row this means we must avoid assigning a ranking value to cells used for labeling purposes let's create an if else if ladder as it were to assign relevant values for each row then let's write code to appropriately call a method that we'll write next named push cell markup to error let's create the push sell markup to our method so the code for this method appropriately populates the cell arrays that we declared earlier on at the top of our code so if the rank num variable is greater than zero we know the cell pertains to a cell that denotes a ranking position in the grid if the value of the rank num variable is not greater than zero this means that the cell is used for labeling purposes and must not be assigned a ranking number so the markup for a cell that is used for labeling purposes is different to a cell that is used for ranking purposes you can see that a cell used for ranking purposes has an ID property that is assigned a value with the rank literal text followed by a dash prefix and this is followed by the cell's ranking value this is how our code will know as it were how to rank an item with an appropriate ranking value once the item has been dragged and dropped into the relevant ranking cell on the ranking grid so let's open the rank items react component and write code to import the ranking grid component into the rank items component let's include the code to call the ranking grid component from within the code responsible for outputting UI related code from the rank items component note that we are passing down the appropriate prop values to the ranking grid component here let's run the code great but in order for the ranking grid to display appropriately we must include the appropriate CSS code within the custom.css file so let's do that great and that is starting to look pretty good let's add code to our custom.css code so that the output of our components aligned centrally on the horizontal axis great so at this point we have a list of items that the user can rank we have also created the functionality for the ranking grid the user ranks an item by dragging and dropping an item onto the appropriate cell on the ranking grid each cell with the exception of the cells used for labeling each row in the ranking grid serves as a ranking position so if a user drags an item onto the top left-hand ranking cell that item's ranking value will be 1. if the user drags an item to the immediate right adjacent top left hand ranking cell the relevant item's ranking value will be assigned a value of 2 and so on the bottom right cell and the ranking grid denotes a ranking value of 16. okay so we want to provide the user with a great user experience so drag and drop functionality will provide the user with an easy and fun way to rank the relevant items so let's create a code to facilitate this functionality note that the code we are about to create unfortunately will not work for touch screens I.E a user will not be able to drag the relevant item by touching the item on the screen and then dragging the item we'll look at how to create drag and drop functionality using a touchscreen device in an upcoming tutorial so the functionality we are providing here allows the user to select the item with the user's Mouse pointer and to drag the item by moving the mouse Pointer while keeping the left Mouse button suppressed and dropping the item into the desired cell by dropping the item at the desired location which is done by releasing the left Mouse button when the mouse pointer is hovered over the relevant ranking cell so to achieve the desired drag and drop functionality let's first create a method named drag the code for this method is just one simple line of code this line of code simply stores the ID value of the item that is being dragged we'll look at how we are able to retrieve this value in just a bit when we discuss the method responsible for the drop functionality okay let's create a function named allow drop so in this method our code EV dot prevent default indicates that the default event that would ordinarily be fired should be canceled for the Target element so with this code we are indicating that we are overriding the default Behavior here so let's write the event handler function for the drop method let's name the method drop so firstly we are writing code to cancel the default event our code then references the target element I.E the element where we wish to drop the dragged element so if an image element already exists as a child element within the target element I.E where we are attempting to drop an item we want to disallow this action so if the user is attempting to drop an item onto an already existing image element we want code to execute in this case to return control back to the calling code without executing any further code in our drop method so let's appropriately include return false here then let's also check to see if the target element contains any child elements we only want the drop functionality to be performed successfully if the target element does not contain any child elements so for example this logic prevents the user from dragging an element over an already existing image in the relevant ranking cell if the target element does not contain any child elements we want code to fire that will cause the relevant item in the items array to be changed accordingly so we want the ranking property of the relevant item to be changed to the ranking value denoted by the cell into which the user is dropping the relevant item we are managing State for the items array by appropriately using the use State hook so the change in value of the ranking property of the relevant item will then trigger our rank items components to be re-rendered which means the image element that the user has dragged onto the ranking grid will remain in the appropriate cell on the ranking grid so once the code has run to change the item's ranking property accordingly we must use the set items method to set the state of the items array like this as discussed the execution of this line of code will trigger the ranking items component to re-render so let's include code within the rank items return section of the component to pass down references to the methods that we have just created as props to the ranking grid component thank you let's appropriately wire up the relevant drag and drop methods to the cells that represent a ranking position on the ranking grid let's include code that adds the relevant image as a child element within the target cell the image represents an item that has its ranking property set to the ranking value denoted by the appropriate grid cell I.E the target cell within the ranking grid remember of course each cell represents a ranking value from 1 to 16. let's open the ranking items JS file and include the relevant drag functionality for the image elements that represent items that the user can Rank by dragging and dropping the items to an appropriate position on the ranking grid so let's test the code okay so that did work but clearly the IMG element is way too large within the relevant ranking cell so let's ensure that we include the appropriate styling code within the custom.css file so that the image element takes up 100 of the height and 100 of the width of its parent cell within the ranking grid let's try that again great but when we drag and drop an item from the item list onto the ranking grid we want the relevant item to disappear from the item list denoting that the relevant item has been ranked it's not currently doing this so we can achieve what we want here by simply including an if condition that checks that only unranked items are included within the item list here all ranked items should appear within the ranking grid so our if condition checks the ranking property for each item if the checked item has a ranking value that is greater than zero then it should appear in the ranking grid and not the item list conversely If an item has a ranking property with a value of zero it should be included within the item list and not appear in the ranking grid so of course one of the great things about modern front-end Technologies like react Blazer or angular is that we are easily able to neatly wrap our code in components I can see within the rank items component an opportunity to further rationalize our code so let's create two more components from the code that we currently have within The Return part of our rank items component so we can abstract the rendering functionality for each item in our items list within its own component we can also abstract the code that traverses each item within the item array into its own component so let's create a component named item that denotes an item within the items array let's create a component named item collection that is responsible for traversing each item in the items array let's write code to import the item component into the item collection component let's write code that traverses each item in the item array in order to appropriately display each item in the user's browser let's write code to import the item collection component into the rank items component and let's write code to call the item collection component from within The Return part of our rank items component so we have now provided functionality so that a user can rank a set of movies by dragging an image from a list of items to a position on a grid that we can refer to as the ranking grid so we have facilitated a drag and drop mechanism for the user that can be utilized to rank the items in the items list so we are able to rank movies at the moment what if we wanted to extend the functionality of our application to enable the ranking of other items for example albums so we are able to easily extend our application so that a user can rank other types of items because we have written our code in such a way that it is extensible we can reuse our components for the purpose of ranking other item types so let's prove this and write code so that a user can rank albums let's first open the item controller class and includes these well-known albums that we'd like the user to rank I've selected a group of well-known albums for this example let's include the relevant albums in our collection of item model objects here notice that the item type property is set to 2 for albums and the item type property for items that represent movies remains one so the item type property in our example distinguishes the types of items stored in our collection on the server if you don't feel like tapping out the code like I'm doing here please feel free to copy the relevant code from this GitHub webpage so the next step is to write code that Imports the images for our albums into our react application so to do this let's first make a copy of the movie images.js file let's rename the copy of the movie images.js file Album images dot Js you can download these Album images from this GitHub webpage we can then copy the relevant downloaded images to a sensible location within our projects we can then appropriately modify our album images.js file so that the images that we have just downloaded are appropriately imported into our react application excellent so we want the user to be able to navigate to the appropriate path where the user can rank the albums so let's first include an appropriate route in the app Root array for this purpose let's open the approot.js file let's modify our code so that two distinct routes are created one route denotes a path relevant to ranking movies The other route defines a path relevant to ranking albums both paths point to a component that we are going to write in just a bit named rank items container this component will be the parent component for the rank items component for the rank movies path we want specific prompt values to be passed down to the rank items contain a component for example the data type prop is appropriately set to 1. now the date type prop on the client is equivalent to the item type property for an item that we have added to a collection on the server so when this route is accessed the state of our application is such that a user can rank movies a value of 2 is being passed down to the rank items container for the rank album path so that the application will be in a state where users can rank albums the user will be able to put the application in these states through clicking the appropriate top menu items on the UI we'll create the code for these navigation menu items in just a bit if you are not clear on the significance of the prop values we are passing down to the rank items container component for each root path don't worry this will become clearer as we progress with the development of this part of the application note that we are passing in the relevant image arrays for each of the relevant paths so we must write code to import the relevant image arrays let's open the file that denotes the nav menu component and appropriately include the relevant nav menu items these items map to the appropriate parts that we have defined within the approot.js file let's create a new file for our rank items container.js functional component in this part of the application we are going to write code to store the state of each collection of items one for movies and one for albums in local storage in the user's browser so at the top we are creating two consts one stores the local storage key for the album collection and the other stores the local storage key for the movie collection let's use the use State hook twice once to track the state of the album collection and the other for tracking the state of the movie collection So based on the dates type value passed into this component we want to set appropriate variables to the appropriate collection and the function that is used for changing the state of the relevant collection the local storage key variable is also set based on the relevant data type value so this if condition is used for altering the state of the application based on the navigation menu item that the user selects IE to rank movies or to rank albums so if the user selects the movies navigation menu item the data type variable will be set to 1. if the user selects the album's navigation menu item the data type variable will be set to 2. a switch between these two values appropriately changes the state of the application I.E for ranking movies or for ranking albums depending on what the user wishes to do in The Return part of the rank items container.js file we can return the rank items component that is being passed the appropriate props we must of course ensure that the rank items component is appropriately imported into the rank items container component let's write code to appropriately destructure the relevant props so we need to modify the use effect hook code here so that the API is a appropriately called when the data type prop value changes the change to the data type prop value means that the user has clicked a navigation menu item to Signal the user's intention to rank items of a different type to the type of items that are currently being ranked or have just been ranked so to do this instead of empty square brackets being passed as the second arguments to our use effect hook we can pass in the data type variable wrapped in square brackets instead like this we can also include another use effect hook so that we can save the state of the relevant collection to local storage every time the relevant item collections State changes in memory we need to check if the relevant items collection is null in the return code here like this note that we are no longer passing in an empty array to the use State hook so if the relevant items collection does not exist in local storage the relevant items collection will be null so the array will be null we also need to check to see if our items collection is null before its new state is written to local storage here let's also abstract a call to the API into its own function like this we only want to call our API if the items collection is null so if the items collection is null call the API to bring down the relevant items collection from the server it is a good idea to clear the items from local storage before we test this code excellent we have now ranked two different types of item sets movies and albums so a user may wish to clear the ranking grid and start the whole ranking process again during a session while ranking the relevant items so this clearing functionality would involve removing all of the items from the ranking grid and all items being loaded back into the non-ranked items list as it were so let's implement the code for this by providing a button that the user can click to reset the items so that if relevant items have been ranked these items will have their ranking values set back to zero to do this we can force our components to make an API call to return the relevant items collection to the client in its original state where none of the items have been ranked so let's add a button to The Return part of the rank items component and let's give our button the caption of reload let's ensure that we are importing the use State hook into this component so two variables are returned from the use statehook the first variable will be used for storing a Boolean value that when set to True means the user has clicked the reload button meaning that the user wishes to reload the relevant items in their original unranked State as discussed this button-click action will force the rank items component to make a call to the API to refresh the items collection from the server so let's Implement code whereby a call is made to the API when the reload variable State changes to true we must also write code to set the reload variable to false when the state of the items collection changes we can of course do this by calling the set reload function appropriately like this let's make our reload button look a little bit better so let's go to this website find a CSS style that we like for our button and let's integrate the copied CSS code you can copy the code simply by clicking on one of the buttons here into our application by including the relevant CSS code in our custom.css file foreign [Music] foreign [Music] and I think that looks pretty great I just want to make a quick Point Sharon this is something that's very easy to forget you should always include a key attribute for elements that are uniquely identifiable in a list of elements this helps react identify changes regarding rendering the relevant component [Music] if you like this video please give this video a thumbs up and please feel free to share this video with anyone you feel May benefit from its content please also consider subscribing to the channel and hit the Bell icon so that you'll be notified of future content I look forward to seeing you soon thank you and take care
Info
Channel: freeCodeCamp.org
Views: 158,911
Rating: undefined out of 5
Keywords:
Id: 4RKuyp_bOhY
Channel Id: undefined
Length: 95min 27sec (5727 seconds)
Published: Tue Jan 03 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.