Hello, I try to use apollo client into my project. I am seeing that sometime when I add new item to list or delete item from list, then I change my page and come back that page, I can see data not updated. Please see this video for better understanding my problem-
Here is my code-
apolloClients.ts -
import { useMemo } from 'react'
import { ApolloClient, HttpLink, InMemoryCache, from, NormalizedCacheObject } from '@apollo/client'
import { onError } from '@apollo/client/link/error'
import { concatPagination } from '@apollo/client/utilities'
import merge from 'deepmerge'
import isEqual from 'lodash/isEqual'
export const APOLLO_STATE_PROP_NAME = '__APOLLO_STATE__'
let apolloClient: ApolloClient<NormalizedCacheObject>
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.forEach(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
)
)
if (networkError) console.log(`[Network error]: ${networkError}`)
})
const httpLink = new HttpLink({
uri: 'http://localhost:3001/ecampus', // Server URL (must be absolute)
credentials: 'include', // Additional fetch() options like `credentials` or `headers`
})
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === 'undefined',
link: from([errorLink, httpLink]),
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
getSections: concatPagination(),
},
},
},
}),
})
}
export function initializeApollo(initialState = null) {
const _apolloClient = apolloClient ?? createApolloClient()
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
// gets hydrated here
if (initialState) {
// Get existing cache, loaded during client side data fetching
const existingCache = _apolloClient.extract()
// Merge the initialState from getStaticProps/getServerSideProps in the existing cache
const data = merge(existingCache, initialState, {
// combine arrays using object equality (like in sets)
arrayMerge: (destinationArray, sourceArray) => [
...sourceArray,
...destinationArray.filter((d) =>
sourceArray.every((s) => !isEqual(d, s))
),
],
})
// Restore the cache with the merged data
_apolloClient.cache.restore(data)
}
// For SSG and SSR always create a new Apollo Client
if (typeof window === 'undefined') return _apolloClient
// Create the Apollo Client once in the client
if (!apolloClient) apolloClient = _apolloClient
return _apolloClient
}
export function addApolloState(client: any, pageProps: any) {
if (pageProps?.props) {
pageProps.props[APOLLO_STATE_PROP_NAME] = client.cache.extract()
}
return pageProps
}
export function useApollo(pageProps: any) {
const state = pageProps[APOLLO_STATE_PROP_NAME]
const store = useMemo(() => initializeApollo(state), [state])
return store
}
And then in _app.tsx
-
export default function App({ Component, pageProps }: AppProps) {
const apolloClient = useApollo(pageProps);
return (
<ApolloProvider client={apolloClient}>
<main className={`${inter.variable} font-sans`}>
<Component {...pageProps} />
</main>
</ApolloProvider>
)
}
After this, I have page named section. In secton.tsx
-
export const getServerSideProps: GetServerSideProps = async (ctx) => {
const apolloClient = initializeApollo()
await apolloClient.query({
query: GET_SECTION_LIST,
variables: { searchInput: {} },
context: {
headers: {
cookie: ctx.req.headers.cookie,
"user-agent": ctx.req.headers["user-agent"],
"x-forwarded-for": ctx.req.socket.remoteAddress
}
},
fetchPolicy: "network-only"
})
return addApolloState(apolloClient, {
props: {},
})
}
In this page I have component named list.tsx
. In this component I try to use data-
const sectionsData = useQuery<GetSectionListData>(GET_SECTION_LIST, { variables: { searchInput: {} } });
Ans lastly here is my query-
export const GET_SECTION_LIST = gql`
query getSections($searchInput: SearchInput!) {
getSections(searchInput: $searchInput) {
id
name
createdBy {
name
phone
}
}
}
`;
Please help me. I need help.