React-apollo: [Query component][Feature request]: Provide way to initialize local state with data

Created on 28 Mar 2018  路  4Comments  路  Source: apollographql/react-apollo

I'm struggling to migrate code from the classic HoC-style to the Query component. I'm working on a basic form which shows a selection field of regions. In the old style I used componentWillReceiveProps to update my local state with an array with just the id of the first selectable item. This way, on initial loading, the first value was preselected.

As the new API is entirely in the render function (which should be pure), I'm not allowed to do any changes to the state (be it classic react state or redux/apollo-link-state). So the only option that I could find, would be to stack another component inside Query and use componentWillReceiveProps there, which seems like a lot of boilerplate for such a simple use-case.

Idea / Possible solution

If the Query-component would provide an onCompleted-callback, developers could use that function to do state-Changes which require knowledge of remote data.

<Query query={...} onCompleted={this.selectFirstElementInLocalState}> ... </Query>

But maybe there is another solution that I could not come up with?

Best regards!

Version

feature

Most helpful comment

Have the exact same need and also used a wrapper component as a work around.
Porting the onCompleted prop from the Mutation component to the Query component seems like a reasonable solution as Johannes has suggested. I can try to put together a PR unless there is a reason not to. Thoughts?

All 4 comments

Have the exact same need and also used a wrapper component as a work around.
Porting the onCompleted prop from the Mutation component to the Query component seems like a reasonable solution as Johannes has suggested. I can try to put together a PR unless there is a reason not to. Thoughts?

https://github.com/apollographql/react-apollo/pull/1922 addresses this and has been merged (and will be included in the next react-apollo release, currently scheduled for June 3rd). Thanks all!

Do you mean *July 3rd ??

Yes 馃槼 - thanks for catching that @windgaucho!

Was this page helpful?
0 / 5 - 0 ratings