1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Leverage the Algolia JS API Client to Display Raw Hits from the API Response

    Raphael TerrierRaphael Terrier
    algoliaAlgolia

    We now have a good understanding of the API Response structure, we could go playing with instantsearch JS library right away, that said this Library is building on top of the JS API Client. To get a better grasp on how it works at a lower level, let’s play first with raw hits straight from the JS API client, we’ll take care of better UI with Instantsearch JS right after that.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: Let's play with the API response and display some results on the page. The first step is to import the Algolia search library into our HTML page. Then, in the body tag, we'll add an empty div tag with an ID of app that we will use to inject the results.

    Below, we will open a script tag. We'll first need a reference to our app div tag, so we can insert the results there once we have them. Now, we can initialize the client with the Algolia search object that is available to us from the library we've imported.

    We pass it an app ID and an API key and assign that to an Algolia constant. Our client is now ready and can communicate with its Algolia application. Search queries are made at the index level, so we need access to a specific index from our app.

    To initialize our index, we'll use the initIndex method, passing it the index name I want to target, here instantsearch. The final step is to perform a call to our Algolia index and display results to the page.

    For that, we'll use the search method on our index object, passing it the query, here an empty string. It returns to us a promise that, once fulfilled, will give us access to the API response. Here, let's call it "results."

    Once we have the response object, we can do pretty much what we want with it. Let's first simply console.log the result and see how it looks like. Heading back to our index page, reloading, and opening the console tab, we can see that our response is properly logged.

    Let's actually do something useful with our results. We'll simply display the name of each product in a paragraph tag. To do so, we'll iterate over the hits array of our results object and assign the resulting array to a hits constant.

    Then, for each hit, we return a simple string literal that consists of the p tag holding the hit name. Finally, we'll use our ref to our app div tag and insert in the innerHTML the hits array using join. Back to our browser, we can now see our product's name displayed on the page.