Skip to content

Commit

Permalink
Add apollo state func (#19137)
Browse files Browse the repository at this point in the history
The intention is to show people the correlation between things, in this case, understand the usage of the same key from the props and the rehydration.

Hopefully, this change will bring value as it has done with some Juniors already.
  • Loading branch information
yordis authored Nov 15, 2020
1 parent 7374d4f commit 1e3534e
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 9 deletions.
15 changes: 13 additions & 2 deletions examples/with-apollo/lib/apolloClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client'
import { concatPagination } from '@apollo/client/utilities'
import merge from 'deepmerge'

export const APOLLO_STATE_PROP_NAME = '__APOLLO_STATE__'

let apolloClient

function createApolloClient() {
Expand Down Expand Up @@ -47,7 +49,16 @@ export function initializeApollo(initialState = null) {
return _apolloClient
}

export function useApollo(initialState) {
const store = useMemo(() => initializeApollo(initialState), [initialState])
export function addApolloState(client, pageProps) {
if (pageProps?.props) {
pageProps.props[APOLLO_STATE_PROP_NAME] = client.cache.extract()
}

return pageProps
}

export function useApollo(pageProps) {
const state = pageProps[APOLLO_STATE_PROP_NAME]
const store = useMemo(() => initializeApollo(state), [state])
return store
}
2 changes: 1 addition & 1 deletion examples/with-apollo/pages/_app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ApolloProvider } from '@apollo/client'
import { useApollo } from '../lib/apolloClient'

export default function App({ Component, pageProps }) {
const apolloClient = useApollo(pageProps.initialApolloState)
const apolloClient = useApollo(pageProps)

return (
<ApolloProvider client={apolloClient}>
Expand Down
10 changes: 4 additions & 6 deletions examples/with-apollo/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import PostList, {
ALL_POSTS_QUERY,
allPostsQueryVars,
} from '../components/PostList'
import { initializeApollo } from '../lib/apolloClient'
import { initializeApollo, addApolloState } from '../lib/apolloClient'

const IndexPage = () => (
<App>
Expand All @@ -25,12 +25,10 @@ export async function getStaticProps() {
variables: allPostsQueryVars,
})

return {
props: {
initialApolloState: apolloClient.cache.extract(),
},
return addApolloState(apolloClient, {
props: {},
revalidate: 1,
}
})
}

export default IndexPage

0 comments on commit 1e3534e

Please sign in to comment.