Reputation: 23213
Im using Apollo Client 2 with React. Is there a callback for when a query has finished loading?
Im making a user's account page. The email field should display the users email. I can get this value with my graphQL query but the loading only finishes after the component has already mounted. I therefore cant use componentDidMount. Is there callback or event I use to setState and populate the email field that way?
import React from 'react';
import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
class AccountPage extends React.Component {
render() {
if (this.props.data.loading) return <p>Loading...</p>;
return(
<form>
<input type="email" />
</form>
)
}
}
const UserQuery = gql`
query UserQuery {
user {
_id
email
}
}
`;
export default graphql(UserQuery)(AccountPage);
Upvotes: 1
Views: 1743
Reputation: 84877
There's a neat way to get around that with recompose:
const LoadingComponent = () => <p>Loading...</p>
compose(
// with compose, order matters -- we want our apollo HOC up top
// so that the HOCs below it will have access to the data prop
graphql(UserQuery),
branch(
({ data }) => {
return !data.user && data.loading
},
renderComponent(LoadingComponent)
),
// BONUS: You can define componentDidMount like normal, or you can use
// lifecycle HOC and make AccountPage a functional component :)
lifecycle({
componentDidMount() {
// set your state here
},
}),
)(AccountPage)
branch
will conditionally render whatever component you pass to it instead of the wrapped component. In this case, the wrapped component is everything below branch inside of compose. That means AccountPage
is not mounted until data.loading
is false and data.user
is truthy, which lets us use componentDidMount to set the state based on the query result.
Upvotes: 3