Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Apollo dynamically create query from state

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

like image 231
Ziker Avatar asked Jun 15 '18 09:06

Ziker


2 Answers

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 :)

like image 80
A. Moynet Avatar answered Nov 16 '22 21:11

A. Moynet


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.

like image 38
Lafi Avatar answered Nov 16 '22 21:11

Lafi