使用Apollo useMutation挂钩传递变量

时间:2020-01-10 23:25:34

标签: reactjs graphql react-hooks apollo react-apollo

我正在使用useMutation挂钩在我的应用程序中提交表单数据。我需要传递组件第一次渲染时未知的数据,因此我试图使用useMutation钩子返回的函数传递复杂的对象。我正在按照Apollo文档(https://www.apollographql.com/docs/react/data/mutations/)中的示例进行操作,但是却遇到400网络错误,我认为这与我的变量传递不正确有关。当我对突变中的数据进行硬编码时,它就可以工作。

component.js

import Test.QuickCheck
import qualified Data.List (nub, partition, sort)
import Data.List (nub, sort)

data Set a = Leaf | Node a (Set a) (Set a) deriving (Show)

partition :: (a -> Bool) -> Set a -> (Set a, Set a)
partition _ Leaf = (Leaf, Leaf)
partition f (Node x l r)
  | f x       = (Node x l1 r1, combine l2 r2)
  | otherwise = (combine l1 r1, Node x l2 r2)
  where (l1, l2) = partition f l
        (r1, r2) = partition f r

        combine Leaf r' = r'
        combine (Node x l r) r' = Node x l (combine r r')

insert :: (Ord a) => a -> Set a -> Set a
insert x Leaf = Node x Leaf Leaf
insert x (Node y l r) = case compare x y of
  LT -> Node y (insert x l) r
  GT -> Node y l (insert x r)
  EQ -> Node y l r

fromList :: (Ord a) => [a] -> Set a
fromList = foldr insert Leaf

toList :: (Ord a) => Set a -> [a]
toList Leaf = []
toList (Node x l r) = toList l ++ x : toList r

prop_partition :: [Int] -> Bool
prop_partition lst =
  let (l, r) = Main.partition even (fromList lst') in (toList l, toList r)
  == Data.List.partition even (sort $ lst')
  where lst' = nub lst

main = quickCheck (withMaxSuccess 10000 prop_partition)

(selectedLines来自此处的React Context,已从组件中的表单更新)

mutation.js

  const [sendLineItems, { loading, data, error }] = useMutation(CANCEL_LINE_ITEM);

  export const structureCancelLineInput = (data) => {
    return {
      request: {
         requestId: '1234',
         orderLines: Object.values(data).map(line => ({
           cancelRequestQuantity: line.quantity,
           reasonCode: line.reason.code,
           reasonText: line.reason.text,
        }))
      }
    }
  };

  const handleSubmit = () => {
    const request = structureCancelLineInput(selectedLines);
    sendLineItems({ variables: request });
  };

模式

const CANCEL_LINE_ITEM = gql`
  mutation CancelLineItemMutation( $request: CancelLineItemInputV1!) {
    cancelLineItem( input: $request ) {
      id
      eta
      status
    }
  }
`;

我是否缺少语法或对象结构错误?

更新:

如果查看初始错误对象,则会收到以下消息:

input CancelLineItemInputV1 {
    request: cancelLineItemRequest!
}

input cancelLineItemRequest {
    requestId: String,
    orderLines: [cancel_orderLines]
}

input cancel_orderLines {
    cancelRequestQuantity: Int!,
    reasonCode: String!,
    reasonText: String!,
}

我可能是错的,但我认为错误是由于我试图传递自定义对象类型而来的,因为它在仅期望字符串时才起作用。我找不到有人在前端传递自定义对象的示例,而且我不确定POJO(不使用Typescript)如何被键入,尤其是在后端定义的自定义类型。我也不知道如何在没有自定义对象的情况下传递数据。

1 个答案:

答案 0 :(得分:-1)

执行此操作。它应该工作。如果您在graphql查询中注意到它以input作为参数,那么input应该在variable对象中被提及。

  const handleSubmit = () => {
  const request = structureCancelLineInput(selectedLines);
   sendLineItems({ variables: {input: request}});
 };