Reputation: 591
I'm a little new to GraphQL and I'm building an app with React and Apollo Client.
When my app starts I fetch pretty much all the data I'll need with one GraphQL query in the topmost component in my React app. In a component further down the component tree I want to directly fetch a model by its ID. How on earth do I do that?
For example say my initial gql query is:
query User($id: ID!) {
user(id: $id) {
username
todoLists {
id
title
todoList {
todoListId
id
name
updatedAt
todo {
id
title
content
updatedAt
}
}
}
}
How would I then fetch via local cache a todo with an ID of say 1?
Sure I could fetch the whole user again and map over the object but that seems wrong.
I've tried using readQuery but I always end up getting a "Can't find field..." error. Should I be using a local resolver?
Whats best practice?
Any tips with an example would be much appreciated.
Upvotes: 0
Views: 1300
Reputation: 1004
There are a number of ways to do it, but the recommended way would be readFragment.
This would require you to turn the "todo" part of your query into a fragment, but that's probably something you'll want to do anyway.
Using fragments will make it explicit to Apollo that a "todo" is a "todo" is a "todo" regardless of which query it's appearing in. And readFragment / writeFragment let you work with that "todo" directly, without worrying about which query it came in from or which query it needs to write to.
Upvotes: 0