问题描述
我对如何在 graphql 中执行多重变异有点困惑。
我读过有关使用 graphql()
函数或 compose()
函数的文章,但我不明白这些是否是传统方法(第 2 版)
或者仍然是一种有效的方式。
我目前正在使用带有 Grandstack 的 apollo 3.3,在我的组件中,我执行以下操作来执行突变(我使用了 useMutation()
提供的 ApolloClient
钩子)
const CreateFBUser = gql `
mutation CreateFBUser($name: String,$fbId: String!) {
CreateFBUser(name: $name,fbId: $fbId) {
_id
id
fbId
name
}
}
`
function FbUserForm() {
const { id } = useParams()
const [formState,setFormState] = useState({})
const [createFBUser,{data: createData}] = useMutation(CreateFBUser)
const { loading,error,data } = useQuery(FBUser,{
variables: {_id: id}
});
...
..
.
如您所见,我没有使用过 <Query>
之类的组件。
第一个问题:这个组件与阿波罗旧版本有关吗?仍然经常使用还是 useMutation()
hook 是 apollo 3 的首选?
第二个问题:我需要执行与第一个相关的第二个突变,并且我需要从第一个突变生成的 id 来执行第二个
//the first mutation
const CreateFBUser = gql `
mutation CreateFBUser($name: String,fbId: $fbId) {
_id
id
fbId
name
}
}
`
//the second mutation (pseudocode)
const AddFBUserMemberOf = gql`
mutation AddFBUserMemberOf($from: _GroupInput!,$to: _FBUserInput!) {
AddFBUserMemberOf(from: $from,to: $to) {
from
to
}
}
`
此外,应该根据值/变量/其他东西有条件地执行第二次突变
解决方法
渲染道具组件已弃用,不会收到进一步的更新或错误修复according to the docs
对于你的第二个问题; useMutation
返回的变异函数采用 options parameter 中的 onCompleted
属性,该属性在变异成功完成后执行。
const [createFBUser,{data: createData}] = useMutation(CreateFBUser)
const [addFBUserMemberOf] = useMutation(AddFBUserMemberOf)
createFBUser({
variables: {
//...
},onCompleted: (data) => {
// data contains the result of createFBUser
addFBUserMemberOf({
variables: {
//...
}
})
}
})