React Apollo dynamically create query from state

自古美人都是妖i 提交于 2019-12-10 19:03:56

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/50872538/react-apollo-dynamically-create-query-from-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!