I'm actually trying to create a slider in React with some different content through my API that has some different keys to access those contents.
For my graphQL query in my API, I have:
title
excerpt
nombreDeSlides
descriptionNode {
childMarkdownRemark {
html
}
}
description1Node {
childMarkdownRemark {
html
}
}
description2Node {
childMarkdownRemark {
html
}
}
description3Node {
childMarkdownRemark {
html
}
}
And I can access it like data.descriptionNode.childMarkdownRemark.html
but I didn't find a way to change the key "descriptionNode" dynamically to be "description1Node" -- "description2Node" --...
I already have my code in a map that get me my variable index to loop, but I really didn't find a way to put the variable index inside my key name.
So, for the moment, I have a solution that does work for some short lists, it works for my case, but I'm still curious about an other solution that implies having a key dynamically.
My solution is to create an array like this one:
let htmlArray = [
data.description1Node.childMarkdownRemark.html,
data.description2Node.childMarkdownRemark.html,
data.description3Node.childMarkdownRemark.html,
data.description4Node.childMarkdownRemark.html,
data.description5Node.childMarkdownRemark.html,
data.description6Node.childMarkdownRemark.html
];
and use the index htmlArray[index] to get the results.
Thank you if you can find me an other solution to this problem I faced.
Assuming you want all the description nodes for your parent, it might be best if you have a field called descriptionNodes
that returns an array, allowing you to access child nodes by their index.
title
excerpt
nombreDeSlides
descriptionNodes {
childMarkdownRemark {
html
}
}
Then you can look up the children by their index
data.descriptionNodes[0].childMarkdownRemark.html
You could also use query alias' combined with a query variable if you really want to keep your object structure, or want to customize a fixed set of 4 slides independently of the parent object.
title
excerpt
nombreDeSlides
descriptionNode(name: $name0) {
childMarkdownRemark {
html
}
}
description1Node: descriptionNode(name: $name1) {
childMarkdownRemark {
html
}
}
description2Node: descriptionNode(name: $name2) {
childMarkdownRemark {
html
}
}
description3Node: descriptionNode(name: $name3) {
childMarkdownRemark {
html
}
}
Also keep in mind GQL queries are just strings, and you can do all sorts of crazy things with them, although I wouldn't recommend it most of the time.
title
excerpt
nombreDeSlides
${['', 1, 2, 3].map((node) =>
`description${node}Node: descriptionNode(name: ${node}) { ...nodeFields }`
).join('\n')}
fragment nodeFields on descriptionNode {
childMarkdownRemark {
html
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.