gpt4 book ai didi

javascript - 查询后如何更新 Apollo 缓存?

转载 作者:行者123 更新时间:2023-12-04 10:41:24 25 4
gpt4 key购买 nike

如何覆盖 Apollo 缓存中的值?

我有一个 graphql 查询来获取用户。这将返回具有默认货币的用户。然后可以从选择下拉列表中覆盖此货币。

查询获取 paymentCurrencies来自 API,然后使用客户端解析器设置 paymentCurrencies 数组中的第一项。成为用户 currency

query me {
me {
username
currency @client
paymentCurrencies
}
}

当有人从下拉菜单中选择一种货币时,我想用他们选择的任何货币来覆盖用户货币。

到目前为止,我有这样的事情:
const onChange = e => {
const { value } = e.target
client.writeData({ user: { currency: value, username, __typename: "User" } })
}

我收到以下错误: Error writing result to store for query:
{"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GeneratedClientQuery"},"selectionSet":null}]}
Cannot read property 'selections' of null

正在使用 writeData是正确的方法还是我应该使用 writeQuery或者其他的东西?

最佳答案

如另一个答案中所述,您可能需要一个简单的查询和变异设置。客户端指令用于扩展您的架构以保存仅限客户端的附加数据。从您的解释来看,您似乎明确希望这些数据与服​​务器同步。

const ME_QUERY = gql`
query me {
me {
username
currency
paymentCurrencies
}
}
`;

const CURRENCY_MUTATION = gql`
mutation setCurrency($currency: String) {
setCurrency(currency: $currency) {
me {
username
currency
}
}
}
`;

function MyComponent() {
const { data } = useQuery(ME_QUERY);
const [setCurrency] = useMutation(CURRENCY_MUTATION);

const onChange = e => setCurrency({
variables: { currency: e.currentTarget.value },
});

return (
<>
<h2>{data && data.me.currency}</h2>
<select onChange={onChange}>
{/* your dropdown logic */}
</select>
</>
);
}

你明白了。 Apollo 现在将自动更新您的缓存。确保您的突变允许查询更新的用户对象。

为了使自动更新工作 您的用户需要被缓存识别 .您可以通过添加一个 id 字段并在查询和突变中选择它或实现 dataIdFromObject 来做到这一点。 Apollo Client 2.x 中的函数,包括 __typename === 'User' 的用户名或者通过在 Apollo Client 3.x 中使用类型策略。找到 docs here .

关于javascript - 查询后如何更新 Apollo 缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59909944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com