I use react 16.13 and am currently migrating from apollo-client
2.x to @apollo/client
3.1.1. I removed a lot of dependency libraries from my packages.json
because most of them are now directly importable from @apollo/client
. Everything was going fine until I tossed a big rock named "removal of defaults" while migrating from apollo-link-state
.
With @apollo/client
3.x, we import InMemoryCache
from @apollo/client
directly, which is fine. But the withClientState
link is no longer existent and ApolloClient
doesn't support default values for local cache. I could not find any guide covering this problem. There is one guide for Angular, but it advises to use cache.writeData
to construct the cache. Only problem is, in v3.x of @apollo/client
, InMemoryCache
doesn't have a writeData
method anymore. There is a modify
method but it is also not straightforward to use, at least I was not able to make it work for this purpose.
I have a large "defaults" object:
export default {
authentication: {
__typename: 'authentication',
auth: ''
},
UserInfo: {
__typename: 'UserInfo',
employee: {
__typename: 'UserInfoEmployee',
defaultShopId: '',
id: '',
email: '',
image: {
__typename: 'image',
id: '',
url: ''
},
firstName: '',
lastName: '',
manager: '',
boss: ''
},
countryCode: '',
chainId: ''
},
defaultShop: {
__typename: 'defaultShop',
id: '',
name: '',
timeZone: null
},
locale: {
__typename: 'locale',
locale: getBrowserLocale()
},
countries: {
__typename: 'countries',
data: []
},
Products: {
__typename: 'Products',
guid: 0,
ProductTypes: {
__typename: 'ProductTypes',
TypeNumber: 0,
type: ''
},
legacyConfiguration: false,
version: '1.0.0'
},
location: {
__typename: 'location',
pathname: '',
search: '',
hash: null,
action: '',
key: null,
isQueryActive: false,
query: null
}
}
How should I write these default data into InMemoryCache
without using cache.writeData
?
Use writeQuery
instead.
I believe in v3 they moved towards using a common way for setting a default state.
const query = gql`
query {
authentication @client {
id
__typename
}
...
}`
cache.writeQuery({
query,
data: {
authentication: {
__typename: 'authentication'
...
}
})