【问题标题】:passing props as graphql mutation argument in react在反应中将道具作为graphql突变参数传递
【发布时间】:2021-10-15 02:25:03
【问题描述】:

我的代码如下所示:

interface MutationProps{
  username: any,
  Mutation: any
}
const UseCustomMutation: React.FC<MutationProps> = (MutationProps: MutationProps) => {
  
  
  
  const [myFunc, {data, error}] = useMutation(MutationProps.Mutation);

  useEffect(() => {
    myFunc({variables:{username: MutationProps.username}}) 
    console.log(JSON.stringify(data))
    console.log(JSON.stringify(error, null , 2))
  }, [])
 return data 
}


export const DisplayUser = () => {
  const GET_USER = gql`
  
 mutation GetUser($username: String!){
getUser(username: $username) {
pfp
username
password
age
CurrentLive
ismod
description
fullname
}
}

 `
 const {username} : {username: any} = useParams()
 const MyData = UseCustomMutation(username, GET_USER)
 console.log(JSON.stringify(MyData))

但我得到了这个错误:×

传递给解析器的未定义参数不是有效的 GraphQL DocumentNode。您可能需要使用 >'graphql-tag' 或其他方法将您的操作转换为文档

【问题讨论】:

  • 看来您正在使用打字稿。你没有收到来自UseCustomMutation(username, GET_USER) 的明确类型错误吗?!
  • 另外,不要在MutationProps 界面中使用any。准确!
  • 谢谢@Bergi,我将 GET_USER 的类型更改为 Document 节点,现在它可以工作了

标签: javascript reactjs typescript graphql graphql-js


【解决方案1】:

你的代码是这样的:

interface MutationProps {
  username: string;
  Mutation: any;
}
const UseCustomMutation: React.FC<MutationProps> = ({ username, Mutation }) => {
  const [functionForDoingAction, { data, loading, error }] = useMutation(
    Mutation,
    {
      variables: {
        username,
      },
    }
  );

  useEffect(() => {
    // fn trigger for change data
    functionForDoingAction({
      variables: {
        username: "string_value",
      },
    });
    console.log(JSON.stringify(data));
    console.log(JSON.stringify(error, null, 2));
  }, []);

  if (loading) return "loading...";

  if (error) return `Submission error! ${error.message}`;

  return data;
};

export const DisplayUser = () => {
  const GET_USER = gql`
    mutation GetUser($username: String!) {
      getUser(username: $username) {
        pfp
        username
        password
        age
        CurrentLive
        ismod
        description
        fullname
      }
    }
  `;
  const { username }: { username: string } = useParams();
  const MyData = UseCustomMutation(username, GET_USER);
  console.log(JSON.stringify(MyData));
};

您可以将参数直接传递给他们作为选项参数提供的 useMutation 钩子。或者是从你得到的钩子中直接触发函数。

【讨论】:

  • 您是否安装了graphql-tag 包然后在顶部添加了import gql from 'graphql-tag'?它将 GraphQL 查询字符串解析为标准的 GraphQL AST。
  • 我是从@apollo/client 导入的,这两者有什么区别吗?
  • 不多,但它在错误中推荐。一种是缓存查询的解析结果,因此每次 gql 都从缓存中调用。文档:npmjs.com/package/graphql-tag
猜你喜欢
  • 1970-01-01
  • 2020-04-22
  • 2018-05-22
  • 2017-01-31
  • 2017-09-22
  • 2022-01-24
  • 2017-03-30
  • 2020-07-28
相关资源
最近更新 更多