I need some help using the new Query and Mutation component in Apollo 2.1, especially with multiple queries and mutations.
I have the following problems:
edit 2019/08/24 from the Apollo docs:
The new hooks API for Apollo Client is a simpler way to fetch data in your React app without the boilerplate of render prop components and higher-order components (HOC). We recommend using hooks for all new Apollo code going forward.
original answer: You are supposed to nest them. See this example:
const NumbersWithData = () => (
<Query query={QueryOne}>
{({ loading: loadingOne, data: { one } }) => (
<Query query={QueryTwo}>
{({ loading: loadingTwo, data: { two }}) => {
if (loadingOne || loadingTwo) return <span>loading...</span>
return <h3>{one} is less than {two}</h3>
}}
</Query>
)}
</Query>
);
To help with keeping the nesting manageable, you could check react-adopt. They have an Apollo ToDo App example, where they combine a Query and multiple Mutations.
For this purpose react-apollo
exports a compose
function. Using this function you may cleanly use several component enhancers at once. Including multiple graphql(), or even Redux connect() enhancers.
import { Mutation, compose, graphql } from "react-apollo";
class AddTweet extends Component {
....
....
....
}
export default compose(
graphql(GET_AUTHORS, { name: "getAuthors" }),
graphql(ADD_TWEET, { name: "addTweet" }),
connect(...), // incase you are using Redux
)(AddTweet);
An important note is that compose()
executes the last enhancer first and works its way backwards through the list of enhancers.
One more thing lets say you were using this.props.data
now you will get get undefined
. just console.log(this.props)
and you will see what is happening to props now. You will be having two properties now getAuthors
and addTweet
. So now it will be this.props.name-in-compose.name-of-type-in-typeDefs
i.e. this.props.getAuthors.getUsers
. It took me a bit to figure it out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With