【发布时间】:2021-01-18 09:12:00
【问题描述】:
我正在玩@apollo/client v3 的缓存。这是codesandbox。
我正在使用client.writeQuery 将一个用户添加到缓存的用户列表中,并且查询有一个pollInterval 每隔几秒重新获取一次。
我可以将用户添加到列表中,它会刷新 UI,并且我可以看到 pollInterval 在 Chrome 的 network 选项卡中工作。
问题
我希望用户列表在轮询开始时返回到其初始状态,并覆盖我手动添加到缓存中的用户,但事实并非如此。
阿波罗配置
export const cache = new InMemoryCache();
const client = new ApolloClient({
cache,
link: new HttpLink({
uri: "https://fakeql.com/graphql/218375d695835e0850a14a3c505a6447"
})
});
用户列表
export const UserList = () => {
const { optimisticAddUserToCache, data, loading } = useUserList();
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
<button onClick={() => optimisticAddUserToCache()}>Add User to cache</button>
<ol>
{data?.users.map(user => {
return <li key={user.id}>{user.firstname}</li>;
})}
</ol>
</div>
);
}
使用用户列表
const GET_USER_LIST = gql`
query Users {
users {
id
firstname
}
}
`;
export const useUserList = () => {
const { loading, error, data, refetch } = useQuery(GET_USER_LIST, {
pollInterval: 4000 // It does poll (check chromes's network tab), but it doesn't seem to overwrite the cache
});
const client = useApolloClient();
const optimisticAddUserToCache = () => {
const newUser: any = {
id: `userId-${Math.random()}`,
firstname: "JOHN DOE",
__typename: "User"
};
const currentUserList = client.readQuery({ query: GET_USER_LIST }).users;
// This works, it does add a user, and UI refreshes.
client.writeQuery({
query: GET_USER_LIST,
data: {
users: [newUser, ...currentUserList]
}
});
};
return { optimisticAddUserToCache, loading, error, data, refetch };
};
【问题讨论】:
标签: caching graphql apollo-client polling