简体   繁体   中英

GraphQL _ Apollo-client - pass guery variables directly in component

I'm trying to pass my GraphQL queries's variables directly in my React component.

So far I have tried to pass it :

  • directly in this.props.mutate
  • in client.props
  • in my parent component as a < parentProps variables={props} />
  • vie React.clone
  • in client.query

None of them works, maybe I have forget something.

Currently I have to hardcode it in the options but it privates me of the possibility to dynamically code it :

export default graphql(fetchRecipe, 
        {options: (props) => ({ 
            variables: {  }
        })})(Displayer); 

* Workaround try but fails: the vanishing pattern as following :*

import {...} 

var property; // just declare your property

class YourClass extends Component { 

property = newValue // your property is now available on the Component's scope, 
                    // allowing you to code it dynamically

render(){ {...}

}

export default graphql(query, 
        {options: (props) => ({ 
            variables: { property } // hence pass the value you want in your graphql options's property
        })})(YourClass); 

So I still search how to pass it directly in component, Any hint would be great,

Thanks,

You're probably (?) looking for graphQL usage from inside of components . It's possible with <Query /> and <Mutation /> components. https://www.apollographql.com/docs/react/essentials/queries.html#manual-query can be suitable, too.

It has some drawbacks - composing many queries and mutations is far easier with graphql() .

Redux comes at hand and prove again its awesomness.

I have simply to pass the property in my Redux's state. Then, I pass the property in the variable option direclty vie the ownProps property. Hence, my state can reach the query. I will appreciate if it allow me to dynamically refetch my data now.

Here my reduxContainer.js:

const mapStateToProps = (state) => { 
    return {
    property: state
    }
}
const yourContainer = connect(mapStateToProps)(YourReactComponent)
export default yourContainer

Then, the state's connected query:

export default graphql(YourQuery, 
        {options(ownProps) {
            return {
              variables: { property : ownProps.property}
            }
}})(YourReactComponent); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM