GraphQL

How to display data in front using GraphQL

We can fetch data through GraphQL Schema in 2 ways:

  • Apollo Client Library
  • AJAX

These both are alternate solutions. You can review Apollo Client Document for how to retrieve data using the Apollo Client. Moreover, we prefer to install the Apollo-Boost AMD module which is free open-source, you can get its GitHub repo from here.

In this blog, we would get an idea of fetching data using GraphQL with AJAX and display retrieved data in front of the Magento 2 website.

Step 1: Create GraphQL Schema
Please create GraphQL schema as described in the following blogs:

Step 2: Create XML Layout file
File Path: Mage2/Person/view/frontend/layout/catalog_product_view.xml
We have taken an example in which we are displaying a person’s information on the product view page.

<referenceContainer name="content">
    <referenceContainer name="product.info.main">
        <block class="Mage2\Person\Block\Info"
               name="person.info"
               template="Mage2_Person::info.phtml"
               before="product.info">
        </block>
    </referenceContainer>
</referenceContainer>

Step 3: Create Template file
File Path: Mage2/Person/view/frontend/templates/info.phtml

<div data-bind="scope: 'person-graphql'">

    <!-- ko template: getTemplate() --><!-- /ko -->

    <script type="text/x-magento-init">
        {
            "*": {
                "Magento_Ui/js/core/app": {
                    "components": {
                        "person-graphql": {
                            "component": "Mage2_Person/js/info-graphql",
                            "template": "Mage2_Person/person-info"
                        }
                    }
                }
            }
        }
    </script>
</div>

Step 4: Create Knockout JS file
File Path: Mage2/Person/view/frontend/templates/web/js/info-graphql.js

Step 4:define(['uiComponent', 'jquery', 'ko'], function(Component, $, ko) {
    'use strict';

    return Component.extend({
        defaults: {
            result: ko.observableArray(),
            isEnabled: ko.observable(false)
        },

        initialize: function () {
            this._super();

            var self = this;

            const query = `
query getPersonData($id: Int!) 
{ 
  person(person_id: $id) 
  { 
    person_id
	name
	age
	sort_order
	created_at
  }
}
`;
            const payload = {
                query: query,
                variables: {
                    person_id: 1
                }
            };

            $.ajax({
                url: 'graphql',
                contentType: 'application/json',
                dataType: 'json',
                method: 'POST',
                data: JSON.stringify(payload),
                success: (function (response) {
                    self.result(response.data);

                    if (self.result().person.person_id != null) {
                        self.isEnabled(true);
                    }
                }),
                error: (function (error) {
                    console.log(error);
                })
            });
            return false;
        }
    });
});

Step 5: Create Knockout JS Template file
File Path: Mage2/Person/view/frontend/templates/web/js/template/person-info.html

<!-- ko if: isEnabled -->
<div>
    <h4 data-bind="text: $t('Person Information')"></h4>

    <div>
    	<span data-bind="text: $t('Person Name')"></span>
    	<span data-bind="text: result().person.name"></span>
    </div>

    <div>
    	<span data-bind="text: $t('Person Age')"></span>
    	<span data-bind="text: result().person.age"></span>
    </div>
</div>
<!-- /ko -->

We hope this blog may understandable and useful to you. You can email us at mage2developer@gmail.com if we missed anything or want to add any suggestions. We will respond to you as soon as possible. Happy to help 🙂