This video is available to students only

Fetching the Basket on App Start

In this lesson, we're going to fetch the basket on app start

Project Source Code

Get the project source code below, and follow along with the lesson material.

Download Project Source Code

To set up the project on your local machine, please follow the directions provided in the README.md file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.

Fetching the basket on app start#

In the last lesson, we prepared our StoreContext. We are now ready to use it from anywhere in our application. Let's start from fetching the basket data. Since we are storing our basket data in our database, we can make an API call to fetch the basket data from our server as soon as our application initializes, and our App.tsx file is the best place to make that call. But if you remember, we can't make an api request without the cookie called clientId. So what we can do is check if we have a clientId in our cookie. If yes, we will make an api request.

Now the question is; how can we fetch the cookie from our browser? Well, our document gives us the access to the cookie but the tricky part is extracting it from a bunch of other cookies stored in the browser. There are plenty of libraries which make it pretty straightforward to extract the cookie, but we can do it without them as well. In the script below, there's a function called getCookie; let's paste it inside App.tsx file. This just takes a string parameter which is the name of the cookie. It then checks it in the current cookie. If it finds the name, it returns the value; otherwise, it returns an empty string.

getCookie function

This lesson preview is part of the The newline Guide to Fullstack ASP.NET Core and React course and can be unlocked immediately with a single-time purchase. Already have access to this course? Log in here.

Unlock This Course

Get unlimited access to The newline Guide to Fullstack ASP.NET Core and React with a single-time purchase.

Thumbnail for the \newline course The newline Guide to Fullstack ASP.NET Core and React