Fetching the list of products

Now that we've seen how the client-side route handler function works, let's take a look at the FetchProducts function that is used to make the XHR call to the server and gather the list of products to display on the page:

func FetchProducts(productsChannel chan []*models.Product) {

data, err := xhr.Send("GET", "/restapi/get-products", nil)
if err != nil {
println("Encountered error: ", err)
return
}
var products []*models.Product
json.NewDecoder(strings.NewReader(string(data))).Decode(&products)

productsChannel <- products
}

Here, we use the xhr package to make XHR calls to the server. We call the Send function from the xhr package and specify that our request will be using the GET method, and we will be making the request to the /restapi/get-products endpoint. For the third argument to the function, we pass a value of nil to indicate that we are not sending data in our XHR call. If the XHR call is successful, we will receive JSON data from the server, which will represent a slice of the Product objects. We create a new JSON Decoder to decode the data and store it in the products variable, which we send over the productsChannel. We will be examining the Rest API endpoint that services this XHR call, in the section, The endpoint to get the list of products.

At this point, our web application has attained the goal of being able to render the Products page without causing a full page reload on subsequent interactions with the website. For example, if we were to access the About page at http://localhost:8080/about, the initial page load will be serviced on the server side. If we initiated a subsequent interaction by clicking on the Products link in the navigation menu, the client-side routing will kick in, and the Products page will load, without a full page reload taking place.

In the Verifying client-side routing functionality section, we will show you how you can verify that client-side routing is functioning properly, using the web browser's inspector. Now it's time to implement the client-side route handler for the product detail page.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.2.157