Ani*_*ita 7 mutation reactjs react-apollo
我正在尝试改变一个突变。突变确实存在并且在我的 graphql 操场上运行良好。但是当我在我的反应组件中实现它时,我得到了错误。查询工作正常。顺便说一句,我的代码中需要客户端,所以我绝对必须使用 ApolloConsumer。
我尝试使用 client.mutate 像https://github.com/apollographql/apollo-client/issues/2762
export const LOGIN = gql`
mutation LOGIN($email: String!, $password: String!) {
login(email: $email, password: $password) {
email
}
}
`;
class LoginComponent extends Component{
render(){
return(
<ApolloConsumer>
{client=>{
return(
<Button onClick={()=>{
client
.mutate({
mutation: LOGIN,
variables: {
email: "test@test.com",
password: "test"
}
})
.then(result => {
console.log('result', result)
})
.catch(err => {
console.log("err", err);
alert(err.toString());
});
}}>
OK
</Button>
)
}}
</ApolloConsumer>
)
}
}
Run Code Online (Sandbox Code Playgroud)
我希望获得成功,但我收到错误:GraphQL 错误:无法在类型“突变”上查询字段“登录”。(第 2 行,第 3 列):登录(电子邮件:$email,密码:$password){ ^
同样的问题,我想添加我的 2 美分作为答案:
我对于不同 GraphQL 服务器的不同端点有几个“上下文”。
我正在使用突变钩子,例如:
const THE_QUERY_OR_MUTATION_CODE = gql`
mutation {
myMutation(etc) {
_id
etc
}
}`
const [handlerOrCaller, { loading, error, data } ] =
useMutation(THE_QUERY_OR_MUTATION_CODE);
Run Code Online (Sandbox Code Playgroud)
通过这种方式,我没有给它正确的“上下文”,因此 Apollo Client 正在获取找到的第一个上下文,这当然是另一个端点,并且模式当然没有名为 的突变myMutation。
我的 Apollo 客户端的配置是:
const client = new ApolloClient({
cache: new InMemoryCache({
dataIdFromObject: (object) => object.key || null
}),
link: authLink.concat(splitOne)
});
Run Code Online (Sandbox Code Playgroud)
这splitOne是一个用不同端点以这种方式连接的变量:
const endpointALink = createHttpLink({
uri: process.env.REACT_APP_ENDPOINT_A
});
const ednpointBLink = createUploadLink({
uri: process.env.REACT_APP_ENDPOINT_B
});
const endpointCLink = createUploadLink({
uri: process.env.REACT_APP_ENDPOINT_C
});
const endpointDLink = createHttpLink({
uri: process.env.REACT_APP_ENDPOINT_D
});
const splitThree = split(
(operation) => operation.getContext().clientName === 'context_a',
endpointA,
endpointB
);
const splitTwo = split(
(operation) => operation.getContext().clientName === 'context_b',
endpointC,
splitThree
);
const splitOne = split(
(operation) => operation.getContext().clientName === 'context_c',
endpointD,
splitTwo
);
Run Code Online (Sandbox Code Playgroud)
所以就我而言,正确的方法是使用正确的上下文:
const [handlerOrCaller, { loading, error, data } ] =
useMutation(THE_QUERY_OR_MUTATION_CODE, {
context: { clientName: 'context_c' }
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9005 次 |
| 最近记录: |