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

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

Start a new discussion. All notification go to the author.