, prop , .
react-apollo docs :
, , codeandbox API- GraphQL.
Data.js
import React from 'react';
import PropTypes from 'prop-types';
import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
const Data = ({ data }) =>
<div>
<h2>Data</h2>
<pre style={{ textAlign: 'left' }}>
{JSON.stringify(data, undefined, 2)}
</pre>
</div>;
Data.propTypes = {
active: PropTypes.bool.isRequired,
};
const query = gql`
query SearchAuthor($id: Int!) {
author(id: $id) {
id
firstName
lastName
}
}
`;
export default graphql(query, {
options(ownProps) {
return {
variables: {
// This is the place where you can
// access your component props and provide
// variables for your query
id: ownProps.active ? 1 : 2,
},
};
},
})(Data);
App.js
import React, { Component } from 'react';
import Data from './Data';
class App extends Component {
constructor(props) {
super(props);
this.state = {
active: false,
};
this.handleChange = this.handleChange.bind(this);
}
handleChange() {
this.setState(prevState => ({
active: !prevState.active,
}));
}
render() {
const { active } = this.state;
return (
<div>
<h1>App</h1>
<div>
<label>
<input
type="checkbox"
checked={active}
onChange={this.handleChange}
/>
If selected, fetch author <strong>id: 1</strong>
</label>
</div>
<Data active={active} />
</div>
);
}
}
export default App;