'Dynamic function name in Graphql
I have the following query
const COURSES = gql`
query(
$course: Course!
) {
**english**(course: $course) {
transfers(
options: {
desc: ["count_in", "count_out"]
}
) {
school {
address
symbol
tokenType
}
}
}
}
`
Note the 5th line starting with 'english' so let's say I have 1000 different courses like ['english', 'politics', 'arts', .... 1000th course). How can I make this course name dynamic. I didn't develop the backend so change in schema is not an option for me. how can I avoid duplication by making course name dynamic.
To be clear I want to place variable name at the place of 'english' at line 5 so that this line can behave like below
english(course: $course) {
politics(course: $course) {
art(course: $course) {
anyCourseName(course: $course) {
Update: I'm calling above query using useQuery and passing parameter $course like below
useQuery(
COURSES,
{
variables: {
course, //this serves as variable $course in above query
},
}
)
Solution 1:[1]
const COURSES = (c) => gql`
query(
$course: Course!
) {
${c}(course: $course) {
transfers(
options: {
desc: ["count_in", "count_out"]
}
) {
school {
address
symbol
tokenType
}
}
}
}
const query = COURSES('art')
?
Solution 2:[2]
You can simply do it like this:
const course = "english";
const COURSES = gql`
query(
$course: Course!
) {
${course}(course: $course) {
transfers(
options: {
desc: ["count_in", "count_out"]
}
) {
school {
address
symbol
tokenType
}
}
}
}
`
Or if you have multiple queries:
const courses = [
"english",
"politics",
"art",
"anyCourseName",
];
const queries = courses.reduce((acc, query) => (
acc.concat(`${query}(course: $course) {
transfers(
options: {
desc: ["count_in", "count_out"]
}
) {
school {
address
symbol
tokenType
}
}
}\n`)
), "");
console.log(queries);
then use it in your gql:
const COURSES = gql`
query(
$course: Course!
)
{
${queries}
}
`;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Clem |
| Solution 2 |
