---
title: Add NrqlQuery components to your Nerdlet
source: https://docs.newrelic.com/docs/new-relic-solutions/build-nr-ui/build-ab-app/nrql
---

> #### 💡 TIP
>
> This lesson is part of a course that teaches you how to build a New Relic application from the ground up. If you haven't already, check out the Overview.
>
> Each lesson in the course builds upon the last, so make sure you've completed the last lesson, Present an end test confirmation modal, before starting this one.

In this series, you're building a full-fledged New Relic application that ingests data from a demo service that's running an A/B test. The app shows the A/B test data in interesting ways so that you'll ultimately be able to choose whether Version A or Version B is more effective at accomplishing your business goal: to increase high-quality newsletter subscriptions.

In past tutorials, you created charts to visualize your data, and you organized those charts so you can use and understand them. You also created a form in your app for ending your test once you're confident in the most effective version. Until now, though, you can't gauge which version is more effective because your charts have been showing mock data, such as:

```js
const versionASignups = {
    metadata: {
        id: 'version-a-newsletter-signups',
        name: 'Version A',
        viz: 'main',
        color: 'blue',
    },
    data: [
        { x: 0, y: 0 },
        { x: 10, y: 10 },
        { x: 20, y: 15 },
        { x: 30, y: 5 },
        { x: 40, y: 30 },
        { x: 50, y: 25 },
    ],
}
```

A chart's `data` prop is useful for supplying manually-crafted data like this or even reformatted third-party data. But for many of your charts, you want to show real-time New Relic data. For example, **Newsletter subscriptions by version** should show subscription data, which exists in New Relic's database, NRDB for short.

To query NRDB, you first need to know what data you're looking for. Remember your demo backend service? Well, that service reports a subscription event to New Relic when a user subscribes to a newsletter from your site. You can view these subscription events in New Relic while your demo services are running.

## View Subscription Events in New Relic [#view-subscription]

Before you query NRDB from your charts, experiment with querying data from New Relic's web interface.

1.  From your [New Relic](https://one.newrelic.com) homepage, go to to the **Data explorer** from the top navigation menu.
    [Data explorer](https://docs.newrelic.com/docs/insights/use-insights-ui/explore-data/data-explorer-query-chart-event-data) lets you explore your telemetry data:
    -   metrics
    -   events
    -   logs
    -   traces

        Since the backend submits newsletter subscriptions as events to New Relic, you can see them in this view.
2.  Select **Subscription** from the **Custom events** menu.
    This queries NRDB for subscription event totals per minute over the last 30 minutes and shows that data in a chart.
3.  Click **Dimensions** to see a list of the attributes associated with these subscription events.
    You can filter and group subscription events using these dimensions. Notice the **NRQL** query above the chart. This shows the chart's underlying query, which is based on these dimensions.
    Click the **page-version** dimension to see the query change to group by `FACET page_version`.
    The Data explorer presents two options for filtering and sorting your data:
    -   User interface (UI) selections like the one you've just made
    -   New Relic Query Language (NRQL)

        The UI is useful for quickly filtering data, and it doesn't require you to know NRQL. For your New Relic application, however, you need to use NRQL queries.

        Click the **NRQL** query to navigate to the Query builder.

        Here, you can view and manually edit the query to fetch the data you need.

## Update `NewsletterSignups` with a `NrqlQuery` [#update-newslettersignups]

Before you begin integrating New Relic data in your NR1 app, consult your design guide.

Your New Relic application has eight charts in total, including line charts, pie charts, and table charts. Each of these charts currently shows mock data, but they need to show real data to be useful. First, focus on querying data for the topmost chart: **Newsletter subscriptions per version**.

With the query you've built in the Data explorer, you already have the data you need for this chart.

> #### 💡 TECHNICAL DETAIL
>
> In your query, you fetch subscription totals (`SELECT count(*) FROM subscriptions`), group them by their page version (`FACET page_version`), and focus the timeseries to the past 30 minutes (`SINCE 30 MINUTES AGO TIMESERIES`).
>
> Explore our [documentation](https://docs.newrelic.com/docs/query-your-data/nrql-new-relic-query-language/get-started/introduction-nrql-new-relics-query-language) to learn more about NRQL queries.

Next, you learn how to pass your NRQL query to your **Newsletter subscriptions per version** chart.

1.  Change to the `add-nrql-components/ab-test` directory of the [coursework repository](https://github.com/newrelic-experimental/nru-programmability-course):
    ````sh
    cd nru-programmability-course/add-nrql-components/ab-test
    ```

    This directory contains the code that we expect your application to have at this point in the course. By navigating to the correct directory at the start of each lesson, you leave your custom code behind, thereby protecting yourself from carrying incorrect code from one lesson to the next.

    ````
2.  In `nerdlets/ab-test-nerdlet/newsletter-signups.js`, update the `LineChart` in `NewsletterSignups`. Remove the mock data, and use the NRQL query you built in the Data explorer:
    ````jsx
    import React from "react";
    import { HeadingText, LineChart, NrqlQuery } from "nr1";

    const ACCOUNT_ID = YOUR_NEW_RELIC_ACCOUNT_ID;

    export default class NewsletterSignups extends React.Component {
      render() {
        return (
          <div>
            <HeadingText className="chartHeader">
              Newsletter subscriptions per version
            </HeadingText>
            <NrqlQuery
              accountIds={[ACCOUNT_ID]}
              query="SELECT count(*) FROM subscription FACET page_version SINCE 30 MINUTES AGO TIMESERIES"
            >
              {({ data }) => {
                return <LineChart data={data} fullWidth />;
              }}
            </NrqlQuery>
          </div>
        );
      }
    }
    ```

    <Callout variant="important">
      Make sure you replace `YOUR_NEW_RELIC_ACCOUNT_ID` with your actual New Relic [account ID](/docs/accounts/accounts-billing/account-structure/account-id/).
    </Callout>

    In `NrqlQuery`, you set two props:

    * `accountIds`: The id for the account you query from
    * `query`: The query to perform

    With these, your NR1 app can query the data you want to show in your chart.

    <Callout variant="tip">
      There is a convenience prop for using NRQL to supply data to your charts, called `query`. If you'd rather not use the `NrqlQuery` component, try the `query` prop instead:

      ```jsx
      <LineChart
        accountIds={YOUR_NEW_RELIC_ACCOUNT_ID}
        query="SELECT count(*) FROM subscription FACET page_version SINCE 30 MINUTES AGO TIMESERIES"
      />
      ```

      Keep in mind you must still supply the `accountIds`.
    </Callout>

    ````
3.  Navigate to the root of your Nerdpack at `nru-programmability-course/add-nrql-components/ab-test`.
4.  Generate a new UUID for your Nerdpack:
    ````sh
    nr1 nerdpack:uuid -gf
    ```

    Because you cloned the coursework repository that contained an existing Nerdpack, you need to generate your own unique identifier. This UUID maps your Nerdpack to your New Relic account.

    ````
5.  Serve your application locally:
    ````sh
    nr1 nerdpack:serve
    ```

    ````
6.  Go to <https://one.newrelic.com?nerdpacks=local>, and view your application under **Apps > Your apps**.
    **Newsletter subscriptions by version** now shows real data from New Relic's database rather than the mock data you defined before. Notice that your chart pulls data when your application loads, but does not continue pulling data while the application is open. You can fix this by adding another prop.
    > #### 💡 TIP
    >
    > If something doesn't work, use your browser's debug tools to try to identify the problem.
    >
    > **Make sure you:**
    >
    > -   Copied the code correctly from the lesson
    > -   Generated a new UUID
    > -   Replaced all instances of `YOUR_NEW_RELIC_ACCOUNT_ID` in your project with your actual New Relic [account ID](https://docs.newrelic.com/docs/accounts/accounts-billing/account-setup/account-id)
7.  Add a `pollInterval`:
    ````jsx
    import React from "react";
    import { HeadingText, LineChart, NrqlQuery } from "nr1";

    const ACCOUNT_ID = YOUR_NEW_RELIC_ACCOUNT_ID;

    export default class NewsletterSignups extends React.Component {
      render() {
        return (
          <div>
            <HeadingText className="chartHeader">
              Newsletter subscriptions per version
            </HeadingText>
            <NrqlQuery
              accountIds={[ACCOUNT_ID]}
              query="SELECT count(*) FROM subscription FACET page_version SINCE 30 MINUTES AGO TIMESERIES"
              pollInterval={60000}
            >
              {({ data }) => {
                return <LineChart data={data} fullWidth />;
              }}
            </NrqlQuery>
          </div>
        );
      }
    }
    ```

    <Callout variant="important">
      Make sure you replace `YOUR_NEW_RELIC_ACCOUNT_ID` with your actual New Relic [account ID](/docs/accounts/accounts-billing/account-setup/account-id).
    </Callout>

    The `pollInterval` is the number of milliseconds between chart refreshes. Each time the chart refreshes, it queries fresh data from New Relic. In this case, you refresh every minute.

    ````

## Populate your `PieChart` with `subscription` event data [#populate]

Now that you've seen how to passed New Relic data to **Newsletter subscriptions per version**, it's time to move on to **Total subscriptions per version**. These two charts are similar in that they compare subscription event data grouped by version. The primary differences between **Newsletter subscriptions per version** and **Total subscriptions per version** are:

-   One is a line chart and one is a pie chart
-   One shows timeseries data and one shows all-time totals

1.  In `nerdlets/ab-test-nerdlet/total-subscriptions.js`, update the `TestDistributions` component, removing the mock data and populating the `PieChart` with the same NRQL query you used for **Newsletter subscriptions per version** but with different `TIMESERIES` and `SINCE` clauses:
    ````jsx
    import React from "react";
    import { HeadingText, NrqlQuery, PieChart } from "nr1";

    const ACCOUNT_ID = YOUR_NEW_RELIC_ACCOUNT_ID;

    export default class TotalSubscriptions extends React.Component {
      render() {
        return (
          <div>
            <HeadingText className="chartHeader">
              Total subscriptions per version
            </HeadingText>
            <NrqlQuery
              accountIds={[ACCOUNT_ID]}
              query="SELECT count(*) FROM subscription FACET page_version SINCE 7 DAYS AGO"
              pollInterval={60000}
            >
              {({ data }) => {
                return <PieChart data={data} fullWidth />;
              }}
            </NrqlQuery>
          </div>
        );
      }
    }
    ```

    <Callout variant="important">
      Make sure you replace `YOUR_NEW_RELIC_ACCOUNT_ID` with your actual New Relic [account ID](/docs/accounts/accounts-billing/account-setup/account-id).
    </Callout>

    You don't need the `TIMESERIES` clause because the pie chart only shows numerical data. You don't need the `SINCE` clause because **Total subscriptions per version** needs to show all-time subscription totals.

    ````
2.  With your Nerdpack served locally, [view your application](https://one.newrelic.com?nerdpacks=local) to see your charts serving real data.
    **Total subscriptions per version** now shows all-time subscription totals from both versions of your demo application.
    > #### 💡 TIP
    >
    > If something doesn't work, use your browser's debug tools to try to identify the problem.
    >
    > **Make sure you:**
    >
    > -   Copied the code correctly from the lesson
    > -   Generated a new UUID
    > -   Replaced all instances of `YOUR_NEW_RELIC_ACCOUNT_ID` in your project with your actual New Relic [account ID](https://docs.newrelic.com/docs/accounts/accounts-billing/account-setup/account-id)

Well done! You've configured some charts to query real subscription data from New Relic's database.

## Populate charts with `pageView` event data

Consider the remaining charts that still use mock data:

-   **Total unsubscriptions per version**
-   **Version A - Page views vs. subscriptions**
-   **Version B - Page views vs. subscriptions**
-   **Version A - Page views**
-   **Version B - Page views**
-   **Past tests**

Some of these charts need to show page view data. Fortunately, your demo application creates a custom event for every page view like it does for subscriptions! Since **Version A - Page views vs. subscriptions** and **Version B - Page views vs. subscriptions** require data from two sources, ignore these for now and focus on **Version A - Page views** and **Version B - Page views**.

1.  In `page-views.js`, remove the mock data from `VersionPageViews` and use a `NrqlQuery` component to supply a query:
    ````jsx
    import React from "react";
    import { HeadingText, LineChart, NrqlQuery } from "nr1";

    const ACCOUNT_ID = YOUR_NEW_RELIC_ACCOUNT_ID;

    export default class VersionPageViews extends React.Component {
      render() {
        return (
          <div>
            <HeadingText className="chartHeader">
              Version {this.props.version.toUpperCase()} - Page views
            </HeadingText>
            <NrqlQuery
              accountIds={[ACCOUNT_ID]}
              query={`SELECT count(*) FROM pageView WHERE page_version = '${this.props.version}' TIMESERIES`}
              pollInterval={60000}
            >
              {({ data }) => {
                return <LineChart data={data} fullWidth />;
              }}
            </NrqlQuery>
          </div>
        );
      }
    }
    ```

    <Callout variant="important">
      Make sure you replace `YOUR_NEW_RELIC_ACCOUNT_ID` with your actual New Relic [account ID](/docs/accounts/accounts-billing/account-structure/account-id/).
    </Callout>

    ````
2.  With your Nerdpack served locally, [view your application](https://one.newrelic.com?nerdpacks=local) to see your charts serving real data.
    In these new queries, you fetch `pageView` custom events instead of `subscription` events. You also use a `WHERE` clause to filter to a particular `page_version` rather than a `FACET` to group by `page_version`.
    > #### 💡 TIP
    >
    > If something doesn't work, use your browser's debug tools to try to identify the problem.
    >
    > **Make sure you:**
    >
    > -   Copied the code correctly from the lesson
    > -   Generated a new UUID
    > -   Replaced all instances of `YOUR_NEW_RELIC_ACCOUNT_ID` in your project with your actual New Relic [account ID](https://docs.newrelic.com/docs/accounts/accounts-billing/account-setup/account-id)

Phew, that's a lot of queries, but your application looks great! You're now showing real data in four charts. Remember the two charts you ignored because they require data from two sources?

-   **Version A - Page views vs. subscriptions**
-   **Version B - Page views vs. subscriptions**

You have to handle these differently than you did for the charts you've been dealing with because NRQL has no method for querying data from multiple sources. In the next lesson, you'll learn how to supply data to these two charts.

> #### 💡 COURSE
>
> This lesson is part of a course that teaches you how to build a New Relic application from the ground up. Continue on to the next lesson: Customize NRQL data.
