我有一个登录组件,当提交时,它会调用登录突变并检索用户数据。
当用户数据返回时,我想设置apollo客户端状态,但我被文档弄糊涂了:
我的组件看起来是这样的:
const LOGIN = gql`
mutation login($username: String!, $password: String!) {
login(username: $username, password: $password) {
username
fullName
}
}
`
const Login = () => {
const onSubmit = (data, login) => {
login({ variables: data })
.then(response => console.log("response", response))
.catch(err => console.log("err", err))
}
return (
<Mutation
mutation={LOGIN}
update={(cache, { data: { login } }) => {
}}
>
{(login, data) => {
return (
<Fragment>
{data.loading ? (
<Spinner />
) : (
<Form buttonLabel="Submit" fields={loginForm} onChange={() => {}} onSubmit={e => onSubmit(e, login)} />
)}
{data.error ? <div>Incorrect username or password</div> : null}
</Fragment>
)
}}
</Mutation>
)
}
正如你所看到的,我的突变中有一个更新道具,它接收login
参数,并有我想在apollo客户端的状态下设置的用户数据。
这里的示例将响应写入缓存cache.writeQuery
,但我不确定这是否是我想要做的。我是否不想像本示例中他们更新本地数据那样写入客户端(而不是缓存(?
mutation
的更新属性似乎只接收缓存参数,所以我不确定是否有任何方法可以访问client
而不是cache
。
如何在mutate的更新属性中使用我的突变响应来更新我的apollo客户端状态?
编辑:我的客户:
const cache = new InMemoryCache()
const client = new ApolloClient({
uri: "http://localhost:4000/graphql",
clientState: {
defaults: {
locale: "en-GB",
agent: null /* <--- update agent */
},
typeDefs: `
enum Locale {
en-GB
fr-FR
nl-NL
}
type Query {
locale: Locale
}
`
},
cache
})
使用上下文API
如果您已经使用ApolloProvider 将组件封装在层次结构中更高的位置
-
使用ApoloConsumer
const Login = () => { const onSubmit = async (data, login, client) => { const response = await login({ variables: data }); if (response) { client.whatever = response; } }; return ( <ApolloConsumer> {client => ( <Mutation mutation={LOGIN}> {login => <Form onSubmit={e => onSubmit(e, login, client)} />} </Mutation> )} </ApolloConsumer> ); };
-
与Apollo 一起使用
const Login = client => { const onSubmit = async (data, login) => { const response = await login({ variables: data }); if (response) { client.whatever = response; } }; return ( <Mutation mutation={LOGIN}> {login => <Form onSubmit={e => onSubmit(e, login)} />} </Mutation> ); }; withApollo(Login);
无上下文API
import { client } from "wherever-you-made-your-client";
并在那里引用