6

Heres a model situation I have some fields in my DB lets say color,size,height ...

I can fetch and display these fields to user who can choose these fields and they are afterwards set to components state

What i want to achieve is to dynamically create GQL query (not query variables) from these fields stored in state

Example

//import react gql ....
class MyComponent extends Component {

constructor(props){
   super(props)
   this.state = {
     fields : []
   }
}

render(){
...
}

componentWillMount(){
    fetch(...)
      .then(fields => this.setState({fields}))
   }

}

export default graphql( --->state => CREATE_QUERY_DYNAMICALLY_FROM_FIELDS(state.fields)<----,{..some options})

Is there a way to access components state during query creation ?

Or some other approach ?

Any ideas appreciated

Ziker
  • 877
  • 2
  • 10
  • 30
  • I don't think there is any built-in function for dynamically creating queries, but since the query is just a string you could format that string by yourself. Eg: `\`query{ topLevelField { ${ fields.join(',') } }}\`` Also you should declare the list of fields outside of your react component, if you are going to declare the `graphql` query outside of your component. – zoran404 Jun 15 '18 at 09:46
  • Since ```graphql``` doesn't support dynamic queries, try to use the apollo client and inject the query conditionally or even the declarative [](https://www.apollographql.com/docs/react/why-apollo.html#declarative-data) Component. – Lafi Jun 15 '18 at 09:50
  • @LefiTarik great comment i have upgraded to react-apollo 2.1 and with works like a charm if you write it as an answer i would definitely accept :) – Ziker Jun 20 '18 at 13:50
  • great @Ziker :). – Lafi Jun 20 '18 at 13:55

2 Answers2

5
class MyComponent extends Component {

   constructor(props){
       super(props)
       this.state = {
         fields : []
       }
   }

   render(){
   ...
   }

   componentWillMount(){
       const query = gql`
           query myDynamicQuery {
               viewer {
                   endpoint {
                       ${this.state.fields.join('\n')}
                   }
               }
           }
       `
       this.props.client.query({ query }).then((res) => ...)
   }
}
export default withApollo(MyComponent)

Hope this is working :)

A. Moynet
  • 450
  • 3
  • 8
  • Your suggestion works! In fact, the entire query can be dynamic. I do not know what downstream impact there might be (related to offline or subscriptions). – mabulu Nov 09 '18 at 16:08
2

Since graphql doesn't support dynamic queries, try to use the apollo client and inject the query conditionally or even you could use the declarative <Query .../> Component.

Lafi
  • 1,310
  • 1
  • 15
  • 14
  • 2
    actually graphql **does** support dynamic queries (the query is simply sent as a json payload in the post). I am going to try what @a-moynet suggested working – mabulu Nov 09 '18 at 14:34