Add nested fields in cache typePolicies - Apollo v3
Asked Answered
B

1

8

I am wondering if it is possible to have nested values using typePolicies of the InMemoryCache For now you can define flat fields policies

new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        hello: {
          read() {
            return 'hello'
          },
        },
        hola: {
          read() {
            return 'hola'
          },
        },
      },
    },
  },
})

// query flat local field using apollo
const QUERY_USER_PAGE = gql`
  query UserPage {
      hello
      hola
  }
`

What if I want to have typePolicies that reflect the structure of my App which seems to be a good practice.
Flat structure will have limitations concerning scaling and maintenance for large project..

new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        userPage: {
          hello: {
            read() {
              return 'hello'
            },
          },
          hola: {
            read() {
              return 'hola'
            },
          },
        },
      },
    },
  },
})

// query nested local field using apollo:
const QUERY_USER_PAGE = gql`
  query UserPage {
    userPage @client {
      hello
      hola
    }
  }
`
Balneology answered 8/1, 2021 at 16:24 Comment(3)
I'm having exactly the same question right now. Pity that nested local state is not documented at all in the Apollo docs. Without being able to nest state pieces the feature is very limited.Upanishad
Did anyone find a solution?Clea
Hi everyone, did anyone find a way to do this? Thanks for your help.Sparrowgrass
K
2

You need to add a policy in UserPage instead of Query

new InMemoryCache({
  typePolicies: {
    UserPage: {
      fields: {
        hello: {
          read() {
            return 'hello'
          },
        },
        hola: {
          read() {
            return 'hola'
          },
        },
      },
    },
  },
})
Kettie answered 26/5, 2022 at 18:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.