Hello, I would need to calculate on-the-fly queries filters in order to get data by certain conditions. In order to do that, I would pass these values as variable to GraphQL API, via Apollo Client. I’ve tried with the usual approach, for instance:
// Assuming previous declarations/dependencies definition
gql `
query Test($live: String!) {
{
queryArticleContents(filter: $live, top: 10) {
...ArticlesFragmentsArticleId
data {
...ArticlesFragmentsArticle
}
}
}
}
${Articles.fragments.articleId}
${Articles.fragments.article}
`
But I’m getting the exception;
Expected Name, found {
I think that’s because I’m not starting it as suggested in the docs, something like:
gql `
{
queryArticleContents(filter: 'foo', top: 10) {
// foo...
}
}
`
There’s any chance to achieve this?
Thanks in advance.
Can you post the full query that is sent to the server?
Data fetching component - index.js
import {useQuery} from '@apollo/react-hooks'
import ARTICLE_QUERY from '../backend/queries/articles'
import moment from 'moment'
// Main
const Index = () => {
const {loading, error, data} = useQuery(ARTICLE_QUERY.articles.indexStart, {
// Last 30 days
variables: {
live: "data/date/iv in ('"+ moment().subtract(30, 'days').format() +"', '"+ moment().format() +"z')"
}
});
// Exception check
if (error) {
return <ErrorDb error={error} />
}
// DB fetching check
if (loading) {
return null;
}
const articles = data.queryArticleContents;
return ...
GraphQL Query - articles.js
import gql from 'graphql-tag';
import Articles from './fragments/articles';
// Queries
const ARTICLE_QUERY = {};
ARTICLE_QUERY.articles = {
indexStart: gql `
query Test($live: String!) {
{
queryArticleContents(filter: $live, top: 10) {
...ArticlesFragmentsArticleId
data {
...ArticlesFragmentsArticle
}
}
}
}
${Articles.fragments.articleId}
${Articles.fragments.article}
`
}
export default ARTICLE_QUERY;
GraphQL Fragments - fragments/articles.js
import gql from 'graphql-tag';
// Fragments
const Articles = {};
Articles.fragments = {
articleId: gql `
fragment ArticlesFragmentsArticleId on Article {
id
}
`,
article: gql `
fragment ArticlesFragmentsArticle on ArticleDataDto {
author {
iv {
id
data {
avatar {
iv {
thumbnailUrl
}
}
name {
iv
}
}
}
}
title {
iv
}
subtitle {
iv
}
date {
iv
}
tags {
iv {
id
data {
label {
iv
}
}
}
}
summary {
iv
}
}
`
}
It was caused due to extra couple of brackets:
query Test($live: String!) {
{ // <---
queryArticleContents(filter: $live, top: 10) {
...ArticlesFragmentsArticleId
data {
...ArticlesFragmentsArticle
}
}
} //<--
}
Has become
query Test($live: String!) {
queryArticleContents(filter: $live, top: 10) {
...ArticlesFragmentsArticleId
data {
...ArticlesFragmentsArticle
}
}
}
Then everything is fine now.
1 Like
Great, that you found it out, I am still a little bit of a GraphlQL newbie.
1 Like