GraphQL Playground variables

Hi, in this post we are going to fetch the data of every job and we are going to lear how to use variables in our GraphQL playground.

If you want to read the last post please click here GraphQL returning data by Id

We need this data to get the Job details:

Instead of passing the id (id: “rJKAbDd_z”) we can use variables and for that we need to insert the query at the beginning and an optional name (called the operation name) it doesn’t affect what we got back in the data

Note: naming the query can be used for the backend team, because if there is an error then the operation name will be part of the log of the error message and will be easier to identify what cause the problem.

Ok, to declare variables as part of the query we need to set the variable name with dollar sign at the beginning and the type of that variable like this:

query JobQuery ($id: ID!) { 

Then instead of the id string we need to pass that variable:

But, wait – How can we set the value of this variable in the GraphQL playground? well, GraphQL playground have a panel variable at the bottom

The variable values are set as a separate Json object, so in our case the only variable accepted by our query is the id, so let’s run the query and we are going to have the same data 🙂

So, this type of query can be useful when we wan to run different id with the same query and we can do that without touching the query at all, just changing the id value in the variable panel.

So, let open the request.js file and add the loadJob function to fetch data by every Job, but in this case we need to pass the job id as parameter of the function:

Nice, now the query section will be the same query that we have in our GraphQL playground, so let’s copy the query and paste inside our function:

The next step is pass the id parameter to our query so for this step we are going to insert a comma after the back ticks and then variables keyword that is an object that contain the function parameter in this case the id:

Now we need to go to our client to use the loadJob function in our case the JobDetail component is who need this data:

Nice! now our browser is rendering the data as we want!

Note: remember to run the client & server (npm start)

By Cristina Rojas.