Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add apollo state func #19137

Merged
merged 6 commits into from
Nov 15, 2020
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 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,18 @@ 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 store = useMemo(
() => initializeApollo(pageProps[APOLLO_STATE_PROP_NAME]),
[pageProps[APOLLO_STATE_PROP_NAME]]
)
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