Add the NerdGraphQuery component to an application

20 minutes
This guide steps you through the process of adding the NerdGraphQuery component to a sample transaction overview application. This allows you to query data from your New Relic account and add it to a dropdown menu.

NerdGraph is New Relic's GraphQL implementation. GraphQL has some key differences when compared to REST:

  • The client, not the server, determines what data is returned.
  • You can easily collect data from multiple sources. For example, in a single New Relic query, you can get account information, infrastructure data, and issue a NRQL request.

Note

Before completing this exercise, you can experiment with GraphQL queries in our NerdGraph API explorer.

We also have a 14-minute video that covers the steps below.

Before you begin

To develop projects, you need our New Relic One CLI (command line interface). If you haven't already installed it, do the following:

  • Install Node.js.
  • Complete steps 1–4 of our CLI wizard, and be sure to make a copy of your account ID from step 1 because you’ll need it later.

Note

If you already installed the New Relic One CLI, but you can't remember your account ID, you can re-run the wizard just to get your account ID.

For additional details, see Set up your development environment.

Prepare the sample code

To get started, complete these steps to update the application UUID (unique ID) and run the sample application locally:

Step 1 of 7

If you haven't already done so, clone the example applications from our how-to GitHub repo. Here's an example using HTTPS:

git clone https://github.com/newrelic/nr1-how-to.git

Step 2 of 7

Change to the directory use-nerdgraph-nerdlet:

cd nr1-how-to/use-nerdgraph/nerdlets/use-nerdgraph-nerdlet

Step 3 of 7

In your preferred text editor, open index.js.

Step 4 of 7

Replace <ADD YOUR ACCOUNT ID> with your account id:

Note

Your account ID is available in the CLI wizard (see Before you begin).

this.accountId = <ADD YOUR ACCOUNT ID>;

Step 5 of 7

Change to the /nr1-howto/use-nerdgraph directory:

cd ../..

Step 6 of 7

Execute these commands to update the UUID and serve the sample application:

nr1 nerdpack:uuid -gf
nr1 nerdpack:serve

Step 7 of 7

Once the sample application is successfully served, go to the local New Relic One homepage (https://one.newrelic.com/?nerdpacks=local) and click Use NerdGraph.

Note

If you don't see any launchers, click Your applications.

Use Nerdgraph launcher

After launching the Use NerdGraph application, you see a dashboard that gives an overview of the transactions in your New Relic account:

Screenshot showing the sample transaction application

Add the NerdGraphQuery component

Now you can create a dropdown menu for changing the account the application is viewing. The first step is to import the NerdGraphQuery component into the application's index.js file.

Note

If you need more details about our example below, see the APIs and components page on https://developer.newrelic.com

Step 1 of 3

Add the NerdGraphQuery component into the first StackItem inside of the return in the index.js file:

<NerdGraphQuery query={query} variables={variables}>
{({ loading, error, data }) => {
console.log({ loading, error, data });
if (loading) {
return <Spinner />;
}
if (error) {
return 'Error!';
}
return null;
}}
</NerdGraphQuery>;

Step 2 of 3

The NerdGraphQuery component takes a query object that states the source you want to access and the data you want returned.

Add the following code to your index.js file in the render method:

Note

In the browser console, you can see the data from your query returned in an object that follows the same structure of the object in the initial query.

const query = `
query($id: Int!) {
actor {
account(id: $id) {
name
}
}
}
`;

Step 3 of 3

To take the data returned by the NerdGraph query and display it in the application, replace the return null in the current NerdGraphQuery component with this return statement:

return <HeadingText>{data.actor.account.name} Apps:</HeadingText>;

When you go back to the browser and view your application, you see a new headline showing the name of your account returned from NerdGraph:

App Image

How to use NerdGraphQuery.query

At this point, you implemented the NerdGraphQuery component with the application's render method and displayed the return data within the transaction overview application.

Here's what you need to do next:

  • Query NerdGraph inside of the componentDidMount lifecycle method.
  • Save the returned data for later usage throughout the New Relic One application.

Complete the following:

Step 1 of 2

The following code takes the response from NerdGraph and makes sure the results are processed, stored into the application state, and logged to the browser console for viewing.

Add the following code into the index.js just under the constructor:

componentDidMount() {
const accountId = this.state;
const gql = `{ actor { accounts { id name } } }`;
const accounts = NerdGraphQuery.query({query: gql}) //The NerdGraphQuery.query method called with the query object to get your account data is stored in the accounts variable.
accounts.then(results => {
console.log('Nerdgraph Response:', results);
const accounts = results.data.actor.accounts.map(account => {
return account;
});
const account = accounts.length > 0 && accounts[0];
this.setState({ selectedAccount: account, accounts });
}).catch((error) => { console.log('Nerdgraph Error:', error); })
}

Step 2 of 2

After the data is stored into state, display a selection so users can change accounts and update the application.

To do this, add the following code to index.js for the second StackItem in the return statement:

{
accounts && (
<StackItem>
<Select
value={selectedAccount}
onChange={(evt, value) => this.selectAccount(value)}
>
{accounts.map((a) => {
return (
<SelectItem key={a.id} value={a}>
{a.name}
</SelectItem>
);
})}
</Select>
</StackItem>
);
}

After you complete these steps, look at the application in your browser, and note the following:

  • The dropdown menu displays the data returned from the NerdGraphQuery.query and allows you to select an account.
  • After you select a new account, the application shows data from the new selection.

App Complete

The final index.js file should have code similar to the code below. This completed sample is in your nerdlet final.js.

import React from 'react';
import { PlatformStateContext, NerdGraphQuery, Spinner, HeadingText, Grid, GridItem, Stack, StackItem, Select, SelectItem, AreaChart, TableChart, PieChart } from 'nr1'
import { timeRangeToNrql } from '@newrelic/nr1-community';
// https://docs.newrelic.com/docs/new-relic-programmable-platform-introduction
export default class UseNerdgraphNerdletNerdlet extends React.Component {
constructor(props){
super(props)
this.state = {
accountId: <YOUR ACCOUNT ID>,
accounts: null,
selectedAccount: null,
}
}
componentDidMount() {
const accountId = this.state;
const gql = `{ actor { accounts { id name } } }`;
const accounts = NerdGraphQuery.query({ query: gql })
accounts.then(results => {
console.log('Nerdgraph Response:', results);
const accounts = results.data.actor.accounts.map(account => {
return account;
});
const account = accounts.length > 0 && accounts[0];
this.setState({ selectedAccount: account, accounts });
}).catch((error) => { console.log('Nerdgraph Error:', error); })
}
selectAccount(option) {
this.setState({ accountId: option.id, selectedAccount: option });
}
render() {
const { accountId, accounts, selectedAccount } = this.state;
console.log({ accountId, accounts, selectedAccount });
const query = `
query($id: Int!) {
actor {
account(id: $id) {
name
}
}
}
`;
const variables = {
id: accountId,
};
const avgResTime = `SELECT average(duration) FROM Transaction FACET appName TIMESERIES AUTO `;
const trxOverview = `FROM Transaction SELECT count(*) as 'Transactions', apdex(duration) as 'apdex', percentile(duration, 99, 95) FACET appName `;
const errCount = `FROM TransactionError SELECT count(*) as 'Transaction Errors' FACET error.message `;
const responseCodes = `SELECT count(*) as 'Response Code' FROM Transaction FACET httpResponseCode `;
return (
<Stack
fullWidth
horizontalType={Stack.HORIZONTAL_TYPE.FILL}
gapType={Stack.GAP_TYPE.EXTRA_LOOSE}
spacingType={[Stack.SPACING_TYPE.MEDIUM]}
directionType={Stack.DIRECTION_TYPE.VERTICAL}>
<StackItem>
<NerdGraphQuery query={query} variables={variables}>
{({loading, error, data}) => {
if (loading) {
return <Spinner />;
}
if (error) {
return 'Error!';
}
return <HeadingText>{data.actor.account.name} Apps:</HeadingText>;
}}
</NerdGraphQuery>
</StackItem>
{accounts &&
<StackItem>
<Select value={selectedAccount} onChange={(evt, value) => this.selectAccount(value)}>
{accounts.map(a => {
return (
<SelectItem key={a.id} value={a}>
{a.name}
</SelectItem>
)
})}
</Select>
</StackItem>
}
<StackItem>
<hr />
<PlatformStateContext.Consumer>
{(PlatformState) => {
/* Taking a peek at the PlatformState */
const since = timeRangeToNrql(PlatformState);
return (
<>
<Grid
className="primary-grid"
spacingType={[Grid.SPACING_TYPE.NONE, Grid.SPACING_TYPE.NONE]}
>
<GridItem className="primary-content-container" columnSpan={6}>
<main className="primary-content full-height">
<HeadingText spacingType={[HeadingText.SPACING_TYPE.MEDIUM]} type={HeadingText.TYPE.HEADING_4}>
Transaction Overview
</HeadingText>
<TableChart fullWidth accountId={accountId} query={trxOverview+since} />
</main>
</GridItem>
<GridItem className="primary-content-container" columnSpan={6}>
<main className="primary-content full-height">
<HeadingText spacingType={[HeadingText.SPACING_TYPE.MEDIUM]} type={HeadingText.TYPE.HEADING_4}>
Average Response Time
</HeadingText>
<AreaChart fullWidth accountId={accountId} query={avgResTime+since} />
</main>
</GridItem>
<GridItem className="primary-content-container" columnSpan={6}>
<main className="primary-content full-height">
<HeadingText spacingType={[HeadingText.SPACING_TYPE.MEDIUM]} type={HeadingText.TYPE.HEADING_4}>
Response Code
</HeadingText>
<PieChart fullWidth accountId={accountId} query={responseCodes+since} />
</main>
</GridItem>
<GridItem className="primary-content-container" columnSpan={6}>
<main className="primary-content full-height">
<HeadingText spacingType={[HeadingText.SPACING_TYPE.MEDIUM]} type={HeadingText.TYPE.HEADING_4}>
Transaction Errors
</HeadingText>
<PieChart fullWidth accountId={accountId} query={errCount+since} />
</main>
</GridItem>
</Grid>
</>
);
}}
</PlatformStateContext.Consumer>
</StackItem>
</Stack>
)
}
}

Summary

Now that you completed all the steps in this example, you successfully queried data from your account using the NerdGraphQuery component in two methods:

  1. Using the NerdGraphQuery component inside the application's render method and then passing the returned data into the children's components.
  2. Using the NerdGraphQuery.query method to query data before the application renders.