ApolloClient:如何在服务器更新后同步 Apollo 缓存?
ApolloClient: How to synchronize Apollo cache after update on the server?
我正在尝试在服务器更新后同步 apollo 缓存。
我应该直接写入缓存还是只重新获取更新的数据?
我实际上只是试图重新获取更新的数据,但仍然无法正常工作。
我有一个 programs(title: String)
查询,如果标题为空则获取所有程序,请参见下面的代码:
class Programs extends React.Component {
render() {
const FIND_PROGRAMS = gql`query findPrograms($title: String) {
programs(title: $title) { id title description }
}`
return (
// The query fetch all programs if title is empty
<Query query={FIND_PROGRAMS} variables={{ title: '' }}>
{({ data, error, loading, refetch }) => {
if (loading) return <span>Loading</span>
if (error) return <span>{error.message}</span>
return (
<div>
{ data.programs.map(program => <ProgramSummary program={program} />)}
<button
onClick={() => axios
.patch('path/to/endpoint', payload)
.then(updatedProgram => {
// Should I update the cache myself with something like this ?
// client.writeData(...)
// Or should I refetch only updated Program like this ?
refetch({ title: updatedProgram.title }) // Not working yet
})
}
>
UpdateProgram
</button>
</div>
)
}}
</Query>
)
}
}
我的重新获取不起作用,我应该做错了什么。
请帮忙
我认为非功能性行为是由于您正在尝试更新特定对象(更新数据)传递 GraphQL 对象数组(这是您的查询 returns,因此您的刷新)。我的意思是,您不会要求某人更新某些内容然后给他们一堆东西,您只需提供您想要更新的特定项目。
我建议改用突变来进行更新,有了它,您将像文档所说的那样自动刷新数据,这或多或少是我之前所说的。
"[...] 如果您要更新单个项目,通常不需要更新功能,只要您 return 项目的 ID 和 属性 您更新的[...]".
见https://www.apollographql.com/docs/react/essentials/mutations#update。
希望对你有所帮助。
我正在尝试在服务器更新后同步 apollo 缓存。 我应该直接写入缓存还是只重新获取更新的数据?
我实际上只是试图重新获取更新的数据,但仍然无法正常工作。
我有一个 programs(title: String)
查询,如果标题为空则获取所有程序,请参见下面的代码:
class Programs extends React.Component {
render() {
const FIND_PROGRAMS = gql`query findPrograms($title: String) {
programs(title: $title) { id title description }
}`
return (
// The query fetch all programs if title is empty
<Query query={FIND_PROGRAMS} variables={{ title: '' }}>
{({ data, error, loading, refetch }) => {
if (loading) return <span>Loading</span>
if (error) return <span>{error.message}</span>
return (
<div>
{ data.programs.map(program => <ProgramSummary program={program} />)}
<button
onClick={() => axios
.patch('path/to/endpoint', payload)
.then(updatedProgram => {
// Should I update the cache myself with something like this ?
// client.writeData(...)
// Or should I refetch only updated Program like this ?
refetch({ title: updatedProgram.title }) // Not working yet
})
}
>
UpdateProgram
</button>
</div>
)
}}
</Query>
)
}
}
我的重新获取不起作用,我应该做错了什么。 请帮忙
我认为非功能性行为是由于您正在尝试更新特定对象(更新数据)传递 GraphQL 对象数组(这是您的查询 returns,因此您的刷新)。我的意思是,您不会要求某人更新某些内容然后给他们一堆东西,您只需提供您想要更新的特定项目。
我建议改用突变来进行更新,有了它,您将像文档所说的那样自动刷新数据,这或多或少是我之前所说的。
"[...] 如果您要更新单个项目,通常不需要更新功能,只要您 return 项目的 ID 和 属性 您更新的[...]".
见https://www.apollographql.com/docs/react/essentials/mutations#update。
希望对你有所帮助。