下面是一个使用Apollo Client进行存储清除或重置时保持/重置默认值的示例代码:
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://api.example.com/graphql',
cache: new InMemoryCache(),
});
// 定义默认值
const defaultValues = {
selectedUser: {
__typename: 'User',
id: null,
name: 'No User Selected',
},
};
// 在cache初始化时设置默认值
client.cache.writeData({
data: defaultValues,
});
// 清除存储并重置为默认值
const resetStore = () => {
client.cache.writeData({
data: defaultValues,
});
};
// 查询当前选中的用户
const GET_SELECTED_USER = gql`
query GetSelectedUser {
selectedUser @client {
id
name
}
}
`;
// 更新选中的用户
const updateSelectedUser = (id, name) => {
client.cache.writeData({
data: {
selectedUser: {
__typename: 'User',
id,
name,
},
},
});
};
// 使用示例
client.query({ query: GET_SELECTED_USER }).then((result) => {
console.log('当前选中的用户:', result.data.selectedUser);
});
updateSelectedUser(1, 'John Doe');
client.query({ query: GET_SELECTED_USER }).then((result) => {
console.log('更新后的选中的用户:', result.data.selectedUser);
});
resetStore();
client.query({ query: GET_SELECTED_USER }).then((result) => {
console.log('重置后的选中的用户:', result.data.selectedUser);
});
在这个示例中,我们首先定义了一个默认值对象defaultValues
,其中包含selectedUser
对象作为存储中的默认值。然后,我们在Apollo Client的cache初始化时使用writeData
方法将默认值写入存储。
接下来,我们定义了一个resetStore
函数,它使用writeData
方法将存储清除并重置为默认值。
然后,我们定义了一个查询GET_SELECTED_USER
,用于查询当前选中的用户。我们还定义了一个updateSelectedUser
函数,它接受用户的id和name,并使用writeData
方法将用户信息写入存储。
最后,我们使用client.query
方法进行查询和更新操作,并在控制台输出结果。
注意:为了使这些代码正常工作,你需要安装@apollo/client
和graphql
包,并将https://api.example.com/graphql
替换为你自己的GraphQL API的URL。