...

/

Using Variables in GraphQL Queries

Using Variables in GraphQL Queries

Learn how to use variables in GraphQL queries.

In the first lesson of this chapter, we defined a few routes in our application, all with different rendering components. One of those routes allows us to display all products posted by a particular user.

Using path parameters

If you recall the first lesson of this section, we’ve defined a few routes in our application, all different rendering components. One of these routes that we’ve added allows us to display all products posted by a particular user:

Press + to interact
<Switch>
...
<Route path="/author/:userName">
<ProductsByUser />
</Route>
...
<Route path="/">
<AllProducts />
</Route>
</Switch>

This means that if a user navigates to http://localhost:3000/author/peter, the page should display all products published by a user with the username peter.

When React Router renders a component for a specified path, it’ll pass path arguments to the rendered component. Before implementing a GraphQL query, we need to see how we can read this parameter’s value in our component by using the useParams function.

Press + to interact
import {
useParams
} from 'react-router-dom'
export default function ProductsByUser() {
const { userName } = useParams()
// We can use the "userName" parameter
}

Sending a query

The question is now, how do we pass this parameter to our ...