RBI Tech
Published in

RBI Tech

Tips and Tricks for working with Apollo Cache

Photo by Stephen Walker on Unsplash

Cache Keys

Task:1234: { name: "Go grocery shopping" }
Task:2345: { name: "Go to gym" }
Task:3456: { name: "Learn GoLang" }
ROOT_QUERY:
tasks(name: "G"): [{}, {}, {}]
tasks(name: "Go"): [{}, {}, {}]
tasks(name: "Gol"): [{}]

Fetch Policies

  1. cache-first
  2. cache-and-network
  3. network-only
  4. no-cache
  5. cache-only

cache-first

cache-and-network

network-only

Refetch Queries

useQuery(FETCH_TASKS, { variables: { name: input } })
useMutation(
CREATE_TASK,
{
refetchQueries: [getOperationName(FETCH_TASKS)]
}
)
useMutation(
CREATE_TASK,
{
refetchQueries: [
{ query: FETCH_TASKS, { variables: { name: 'shopping' } } }
]
}
)

Writing to the Cache

useMutation(CREATE_TASK, {
update: (cache, mutationResult) => {
const newTask = mutationResult.data.createTask;
const data = cache.readQuery({
query: FETCH_TASKS, variables: { name: newTask.name }
});
cache.writeQuery({
query: FETCH_TASKS,
variables: { name: newTask.name },
data: { tasks: [...data.tasks, newTask]
})
}
})

Optimistic UI

useMutation(CREATE_TASK, {
update: (cache, mutationResult) => {
const newTask = mutationResult.data.createTask;
const data = cache.readQuery({
query: FETCH_TASKS, variables: { name: newTask.name }
});
cache.writeQuery({
query: FETCH_TASKS,
variables: { name: newTask.name },
data: { tasks: [...data.tasks, newTask]
})
},
optimisticResponse: {
__typename: "Mutation",
createTask: {
__typename: "Task",
_id: `This part we don't know yet but it will be a unique string so just to be safe ${uuid()}`,
name: input.name,
description: input.description,
}
}
})

Busting the Cache

useMutation(CREATE_TASK, {
update: cache => {
cache.evict({
id: "ROOT_QUERY",
field: "tasks"
})
}
}
useMutation(CREATE_TASK, {
update: (cache, mutationResult) => {
const newTask = mutationResult.data.createTask;
cache.evict({
id: "ROOT_QUERY",
field: "tasks",
args: { name: newTask.name }
})
}
})

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store