Shayan Javadi
Shayan Javadi

Reputation: 380

How to pass data from react component to Apollo graphql query?

I'm developing an app using react-native and apollo/graphql.

What I want to do in this case is to do a computation in my component (in this case scanning a barcode) and then pass the results to my graphql query so it can hit our backend api with the barcode and return results.

I've been searching through the apollo docs and google for a few hours now and I'm at a loss.

here's the gist of what I'm trying to do:

class ScanBookScreen extends Component {

  state = {
    hasCameraPermission: null,
  }

  render() {
    return (
      <View style={{ flex: 1 }}>
        <BarCodeScanner
          onBarCodeRead={// pass this to the query down below} <-----
        />
      </View>
    );
  }
}

const lookupTextbooksQuery = gql`
  query lookupTextbooks($query: String) {
    lookupTextbooks (query: $query, limit: 1) {
      totalItems
      textbooks {
        id
        title
        description
      }
    }
  }
`;

export default graphql(lookupTextbooksQuery, {
    options: { variables: { query: // This is the part that needs to come from the component somehow} }, <----

})(ScanBookScreen);

Upvotes: 0

Views: 716

Answers (1)

zackify
zackify

Reputation: 5434

render() {
    let { refetch } = this.props.data
    return (
      <View style={{ flex: 1 }}>
        <BarCodeScanner
         onBarCodeRead={query => refetch({ query })} 
        />
      </View>
    );
}

You would do something like this. If you want to pass the component's props into the initial query, you can do this:

options: props => ({ variables: { query: props.query } })

http://dev.apollodata.com/core/apollo-client-api.html#ObservableQuery.refetch

Upvotes: 1

Related Questions