Unverified Commit 1e3534e1 authored by Yordis Prieto's avatar Yordis Prieto Committed by GitHub

Add apollo state func (#19137)

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.
parent 7374d4ff
......@@ -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() {
......@@ -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,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}>
......
......@@ -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>
......@@ -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
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment