Graphql Read From Cache Before Server Query

Tips and Tricks for working with Apollo Cache

Photograph by Stephen Walker on Unsplash

Cache Keys

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

Fetch Policies

  1. enshroud-beginning
  2. cache-and-network
  3. network-only
  4. no-enshroud
  5. cache-simply

cache-first

cache-and-network

network-only

Refetch Queries

          useQuery(FETCH_TASKS, { variables: { proper 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: { proper noun: newTask.proper name }
});
cache.writeQuery({
query: FETCH_TASKS,
variables: { name: newTask.name },
data: { tasks: [...information.tasks, newTask]
})
}
})

Optimistic UI

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

Busting the Cache

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

Conclusion

mitchelltentons.blogspot.com

Source: https://medium.com/rbi-tech/tips-and-tricks-for-working-with-apollo-cache-3b5a757f10a0

0 Response to "Graphql Read From Cache Before Server Query"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel