[我正尝试在用户退出我的应用程序时清除我的Apollo商店,但没有运气能正确更新所有内容。
目前,我正在根据当前用户的存在条件显示经过身份验证/未经身份验证的路由。终结点依赖于标头中的令牌。此令牌在登录时设置并保持不变。
export default function App() {
const { client, data, loading } = useQuery(CURRENT_USER, {
onCompleted({ currentUser }) {
client.writeData({ data: { currentUser } });
}
});
if (loading) return null;
return (
<BrowserRouter>
{data.currentUser ? <Authenticated /> : <Unauthenticated />}
</BrowserRouter>
);
};
[经过身份验证的用户可以在登录时查看/触摸多种资源,每种资源都有自己的查询。
export default function Zones() {
const { data, loading } = useQuery(ZONES);
if (loading) return null;
return (
<div className='Zones'>
...
</div>
);
}
我面临的问题是,当用户注销时,我无法完全清除商店。在我的signOut
函数中,我正在调用client.resetStore()
,据我了解,该操作将重新获取活动查询,从而使服务器响应未经授权的请求。
const signOut = () => {
localStorage.setItem('token', null);
client.resetStore();
};
[我的困惑是,即使我调整了signOut
以清除商店中的当前用户并将我发送到Unauthorized
容器,当调用resetStore()
时,它也会获取所有过时的查询。
我尝试使用clearStore()
,但我的组件不会重新呈现,并且现有查询仍然存在,所以当这些组件都不存在时,会出现无法读取currentUser
属性的错误了。
我也尝试过client.writeQuery
并将CURRENT_USER
查询更改为不返回任何内容,但其余数据仍然存在,并且如果它是不同的资源查询(例如,由ID拥有的ID,则无法使用)第一用户)。
我仍然对解决此问题的其他方法持开放态度,但这现在对我有用。
这会清除所有过去的数据,然后重新获取原始查询。由于某些原因,如果我使用退出按钮在组件中调用App
或writeData
,我可以not获取writeQuery
查询以进行更新。
export default function App() {
const { client, data, loading, refetch } = useQuery(CURRENT_USER, {
onCompleted({ currentUser }) {
client.writeData({ data: { currentUser } });
}
});
if (loading) return null;
return (
<BrowserRouter>
<CurrentUserContext.Provider value={refetch}>
{data.currentUser ? <Authenticated /> : <Unauthenticated />}
</CurrentUserContext.Provider>
</BrowserRouter>
);
};
const client = useApolloClient();
const refetchCurrentUser = useContext(CurrentUserContext);
const signOut = () => {
localStorage.setItem('token', null);
client.clearStore().then(refetchCurrentUser);
};