Reputation: 305
I've been trying to get related news for articles in GraphQL. Each article has 1 or more tags and based on those tags it needs to find up to 3 related articles with a new query.
Any help would be greatly appreciated.
My query looks like this:
strapiArticles(Slug: { eq: $slug }) {
strapiId
Title
Date
Content
tags {
tag
slug
}
Image {
publicURL
}
}
}
The tags bit looks like:
"tags": [
{
"tag": "Tag 1",
"Slug": "tag-1"
},
{
"tag": "Tag 2",
"Slug": "tag-2"
}
]
I've tried passing the tags in the context but Gatsby doesn't support arrays or object in the context. Like this:
createPage({
path: `news/${edge.node.Slug}`,
component: path.resolve("src/templates/news-post.js"),
context: {
tag: edge.node.tags,
slug: edge.node.Slug,
}
})
Upvotes: 1
Views: 345
Reputation: 29320
but Gatsby doesn't support arrays or object in the context.
That's not true. You can send an array of tags via context but you need to prepare your data first:
let allTagsFromNode= edge.node.tags.map(tag=> tag.tag);
This should return all tag names (tag
) for a specific new within a structure like ["Tag 1", "Tag 2"]
. Tweak it a little bit to get a simple one dimension array if needed.
createPage({
path: `news/${edge.node.Slug}`,
component: path.resolve("src/templates/news-post.js"),
context: {
allTagsFromNode,
slug: edge.node.Slug,
}
})
Note: because you are sending allTagsFromNode
with the same key than the value, you can omit to send it by allTagsFromNode: allTagsFromNode
Then, in your news-post.js
template your query should look like:
export const newsData = graphql`
query getNewsInformation ($slug: String!, $author: String, $allTagsFromNode: [String!]) {
## your news query
relatedArticles: strapiArticles(
filter: {
tags: {elemMatch: {tag: {in: $allTagsFromNode}}},
Slug: {ne: $slug}},
limit: 3) {
edges {
node {
## your node fields
}
}
}
}
`;
Among tweaking the query to adapt it to your needs (since I don't know how your data structure looks like) and also adding the news query, what is important here is that you are sending your tags by $allTagsFromNode
, declared as an array (it's called list in GraphQL) of strings in:
$allTagsFromNode: [String!]
Now, you can query and filter from all your articles to get the related news:
relatedArticles: strapiArticles(
filter: {
tags: {elemMatch: {tag: {in: $allTagsFromNode}}},
Slug: {ne: $slug}},
limit: 3)
You are now filtering all tag names (tag
) that are included in the allTagsFromNode
list.
It's also important to notice that you don't want the same article to be included as related, that's why you are omitting it in Slug: {ne: $slug}}
(using the ne
filter).
Upvotes: 2