apollo-link-state
apollo-link-state copied to clipboard
how to query local state by Id
I'd like to know what's the proper way to query a collection with apollo-link-state
e.g.
if I have a list of todos which initialize to an empty array, and I write a query as follows:
const cache = new InMemoryCache();
const client = new ApolloClient({
cache,
link: new HttpLink({
uri: "http://localhost:4000/graphql",
headers: {
authorization: localStorage.getItem("token"),
"client-name": "Space Explorer [web]",
"client-version": "1.0.0"
}
}),
initializers: {
todos: () => [{ title: "Test", id: v4(), __typename: "Todo" }]
},
resolvers,
typeDefs
});
query GetTodo($id: ID!) {
todo(id: $id) {
id
title
completed
}
}
I tried using a cache redirect, but that didn't work.
@peggyrayzis @stubailo @jbaxleyiii I wish I could help you guys write docs. Is there a way I can directly interact with the apollo team in order to help write docs on Apollo?
Very surprising that a cache redirect didn't work - that's what I would have suggested! I don't work at Apollo as of 3 months ago, but I can help you get docs PRs merged in!
Does this work if you try 2.4
version of ApolloClient? Also what v4()
returns for id and what if you try this with static id?
@jsslai it's just a uuid v4. from the uuid
npm package.
in theory this should "just work" with a cache redirect, but... it doesn't maybe due to something not being setup in apollo-link-state "yet" I'm using the alpha release @peggyrayzis talked about at GraphQL Summit.
Any news on this? I also feel a need for something like
query GetTodo($id: ID!) {
todo(id: $id) {
id
title
completed
}
}
But I don't really know how to do it. Is there any complex example available for some complex local state with queries with parameters. I only saw local-link-state mutations with parameteres, not queries...
For something so basic, information on how to do this is surprisingly hard to come by. I believe this is what you're looking for:
/**
* Apollo link state resolvers
*/
const resolvers = {
Query: {
getTodo: (parent, { id }, { cache, getCacheKey }) => {
return cache.readFragment({
id: getCacheKey({ __typename: 'Todo', id: id }),
fragment: gql`
fragment myTodo on todos {
id
label
description
complete
}
`,
});
}
},
Mutation: {}
};
@tkambler thanks for the solution, but it doesn't solve the case where you call getTodo without all the fields in the fragment it should be deferred to the caller I'd assume.
Did you ever get the solution you were looking for, @lifeiscontent?
@darrylyoung no unfortunately not