Since version 2.1, react-apollo is exposing some new components that use the function-as-child (or render-prop) pattern to let you connect apollo-client magic with your components. See the blog article: [New in React Apollo 2.1](https://www.apollographql.com/docs/react/react-apollo-migration.html)
If I'm not mistaken, it's generally agreed that this pattern is (where it works) superior to the HOC pattern, for reasons that are best explained here: https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce
So I updated the with-apollo example to use the new API, and IMO this code is much simpler and natural to read and understand, especially if you are not already familiar with Apollo's HOC APIs.
I broke up my changes into separate commits, for easier review. Commits with "Refactor" in the message accomplish the goal of switching to the new APIs while minimizing line-by-line differences (select "Hide whitespace changes" under "Diff settings"). Commits with "Clean up" in the message follow up the refactoring with trivial things like reorganizing code sections, renaming variables, etc.
For the components doing mutations, I chose not to use the `Mutation` component, since that doesn't really make sense to me; a mutation is something that happens at a point in time, so it's not meaningful to represent a mutation in the markup, which exists for a period of time. All that component does is expose a `mutate` function for a single specified mutation, and `result` data for a single firing of the mutation (which we don't need anyways; apollo handles updating the local data with the result). To me it seems simpler and more flexible to just get the apollo client via `ApolloConsumer` and call `.mutate()` on it.
In case anyone is interested, here's what my version of `PostUpvoter` using the `Mutation` component looked like:
<details>
```jsx
import React from 'react'
import { Mutation } from 'react-apollo'
import { gql } from 'apollo-boost'
export default function PostUpvoter ({ votes, id }) {
return (
<Mutation mutation={upvotePost}>
{mutate => (
<button onClick={() => upvote(id, votes + 1, mutate)}>
{votes}
<style jsx>{`
button {
background-color: transparent;
border: 1px solid #e4e4e4;
color: #000;
}
button:active {
background-color: transparent;
}
button:before {
align-self: center;
border-color: transparent transparent #000000 transparent;
border-style: solid;
border-width: 0 4px 6px 4px;
content: '';
height: 0;
margin-right: 5px;
width: 0;
}
`}</style>
</button>
)}
</Mutation>
)
}
const upvotePost = gql`
mutation updatePost($id: ID!, $votes: Int) {
updatePost(id: $id, votes: $votes) {
id
__typename
votes
}
}
`
function upvote (id, votes, mutate) {
mutate({
variables: { id, votes },
optimisticResponse: {
__typename: 'Mutation',
updatePost: {
__typename: 'Post',
id,
votes
}
}
})
}
```
</details>
###
I'm happy with where things are at here, but I'm more than happy to address any comments, concerns, ideas for improvent!
Thanks!
As seen on `with-apollo-auth` there are some things that need to be addressed here too.
* #4554 remove useless `apolloState` from App props on `getDataFromTree`
* #4563 simplify `apolloState` prop
Let me know if further changes/fixes are needed.
Thank you 🎉
Apollo's getDataFromTree is supposed to be called during the server side rendering.
Being called in browser it fires an unnecessary fake render process and blocks components from rendering with loading=true.
Also there was a mistake in this code:
// `getDataFromTree` renders the component first, the client is passed off as a property.
// After that rendering is done using Next's normal rendering pipeline
this.apolloClient = props.apolloClient || initApollo(props.apolloState.data)
**Apollo** component is not rendered by getDataFromTree actually, it renders the **App** directly, thus props.apolloClient will always be undefined.
This example was discussed here: https://github.com/zeit/next.js/issues/387.
I had some trouble to get server side rendering with the AWSAppSyncClient working. I finally found a solution in https://github.com/awslabs/aws-mobile-appsync-sdk-js/issues/82 but it might be worth to share it here as well. Instead of adding a big code block to each file I'll just refer to this Pull Request.
______
In case you want to use the `AWSAppSyncClient` you just need to replace the `create()` function with this function:
```jsx
import AWSAppSyncClient from 'aws-appsync';
import { AUTH_TYPE } from 'aws-appsync/lib/link/auth-link';
function create(initialState) {
const client = new AWSAppSyncClient({
url: AWS_AppSync.graphqlEndpoint,
region: AWS_AppSync.region,
auth: {
type: AUTH_TYPE.API_KEY,
apiKey: AWS_AppSync.apiKey,
// Amazon Cognito Federated Identities using AWS Amplify
//credentials: () => Auth.currentCredentials(),
// Amazon Cognito user pools using AWS Amplify
// type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS,
// jwtToken: async () => (await Auth.currentSession()).getIdToken().getJwtToken(),
},
disableOffline: true,
}, {
cache: new InMemoryCache().restore(initialState || {}),
ssrMode: true
});
return client;
}
```
* Add new apollo example
* Update readme
* Update with-apollo to use _app.js
* Move withData to _app
* Make SSR work again
* Remove withData
* Use HOC to provide apolloClient
* Spread pageprops
* Examples: clarify language around Yarn create & npx
* add missing READMEs and create-next-app usage
* suggest people tag jthegedus in firebase related issues
* add yarn alt instructions
* cerebraljs example readme & fixes
This was causing react-apollo to crash on any SSR page that needed the page's query to make the GraphQL queries.
It's magically passed on the client, but we have to manually pass it to the composed component here
* pass down getInitialProps ctx to ComposedComponent
* pass apollo client instance directly to getDataFromTree instead of through the ApolloProvider wrapper.
* Avoid redundant empty serverState initialization (It's always initialized)
* remove global npm install of create-next-app
* add npx to create-next-app command in examples
* add bash to shell snippets
* add yarn create to next-app command in examples
* fix READMEs named with lowercase
* change READMEs to use UPPERCASE
The serverState variable definition did not include the data node, which
may cause parsing errors on the client-side.
- add data: { } on line 23 within the apollo: { } object
Prior to react-apollo 2.0 createNetworkInterface accepted the credentials option in {opt: {credentials: 'policy'}}. HttpLink accepts it as {credentials: 'policy'}.
* [fix] with-apollo: Cannot read property 'data'
When we create the initial serverState, we need to create the
eventual construct of the Apollo Data to reside within
Later in the constructor this allows for the initApollo to either
be generated from SSR, or to init from scratch.
Fixes
> Cannot read property 'data' of undefined
> TypeError: Cannot read property 'data' of undefined
* [refactor] with-apollo: reduce init `serverState`
No need to explicitly set `data` as empty.
This trims up 4 lines. 😀️
* Updated dependencies related to Apollo and React.
* Updated libs with Apollo 2 new set of modules.
* Updated to Apollo 2 react integration modules.
* Updated withData to separate apollo state from the app's state.
* Add minimal apollo example
* Update apollo example README
* Update apollo example demo link in README
* Fix button styles
* Fix show more button
* Alias demo url
* Include the data field on the Apollo store when hydrating
* Revert
* Include the data field on the Apollo store when hydrating per tpreusse's suggestion.
* Add example to faq section in README
* Sort by newest; Add active state to buttons
* Make optimization suggestions
* Use process.browser; inline props
* Pass wrapped component's initial props into component heirarchy if they exist
* Remove unnecessary sorting of array
* Update Apollo example
* Remove trailing comma
* Update reduxRootKey
* Remove unnecessary babelrc
* Update with-apollo example
- Remove use of deprecated 'reduxRootKey' option
- Add loading indicator inside pagination button
* Fix with-apollo example pagination; Pass initialState to ApolloClient
* Split apollo example into two (one with and without Redux integration)
* Rename createClient private function to _initClient
* Set initialState default parameter inside initClient function
* Remove redux dep from with-apollo example
* Add minimal apollo example
* Update apollo example README
* Update apollo example demo link in README
* Fix button styles
* Fix show more button
* Alias demo url
* Include the data field on the Apollo store when hydrating
* Revert
* Include the data field on the Apollo store when hydrating per tpreusse's suggestion.
* Add example to faq section in README
* Sort by newest; Add active state to buttons
* Make optimization suggestions
* Use process.browser; inline props
* Pass wrapped component's initial props into component heirarchy if they exist
* Remove unnecessary sorting of array
* Update Apollo example
* Remove trailing comma
* Update reduxRootKey
* Remove unnecessary babelrc
* Update with-apollo example
- Remove use of deprecated 'reduxRootKey' option
- Add loading indicator inside pagination button
- Deleted several unused dependencies.
- Updated dependencies.
- Simplified Apollo related imports thanks to react-apollo exporting apollo-client and graphql-tag since [v0.13.2](https://github.com/apollographql/react-apollo/blob/master/Changelog.md#0132).
- Tidied the readme and added a link to the Apollo docs.
* Add minimal apollo example
* Update apollo example README
* Update apollo example demo link in README
* Fix button styles
* Fix show more button
* Alias demo url
* Include the data field on the Apollo store when hydrating
* Revert
* Include the data field on the Apollo store when hydrating per tpreusse's suggestion.
* Add example to faq section in README
* Sort by newest; Add active state to buttons
* Make optimization suggestions
* Use process.browser; inline props
* Pass wrapped component's initial props into component heirarchy if they exist
* Remove unnecessary sorting of array
* Update Apollo example
* Remove trailing comma
* Update reduxRootKey
* Remove unnecessary babelrc
* Add minimal apollo example
* Update apollo example README
* Update apollo example demo link in README
* Fix button styles
* Fix show more button
* Alias demo url
* Include the data field on the Apollo store when hydrating
* Revert
* Include the data field on the Apollo store when hydrating per tpreusse's suggestion.
* Add example to faq section in README
* Sort by newest; Add active state to buttons
* Make optimization suggestions
* Use process.browser; inline props
* Pass wrapped component's initial props into component heirarchy if they exist
* Remove unnecessary sorting of array
* Add minimal apollo example
* Update apollo example README
* Update apollo example demo link in README
* Fix button styles
* Fix show more button
* Alias demo url
* Include the data field on the Apollo store when hydrating
* Revert
* Include the data field on the Apollo store when hydrating per tpreusse's suggestion.
* Add example to faq section in README
* Sort by newest; Add active state to buttons
* Make optimization suggestions
* Use process.browser; inline props
* Pass wrapped component's initial props into component heirarchy if they exist
* Add minimal apollo example
* Update apollo example README
* Update apollo example demo link in README
* Fix button styles
* Fix show more button
* Alias demo url
* Include the data field on the Apollo store when hydrating
* Revert
* Include the data field on the Apollo store when hydrating per tpreusse's suggestion.
* Add example to faq section in README
* Sort by newest; Add active state to buttons
* Make optimization suggestions
* Use process.browser; inline props