在react中将props作为graphql突变参数传递

问题描述 投票:0回答:2

我的代码如下所示:

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' 或其他方法将您的操作转换为文档

javascript reactjs typescript graphql graphql-js
2个回答
0
投票

你的代码看起来像这样怎么样:

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 挂钩,它们作为选项参数提供。或者是从你得到的hook直接触发的功能。


0
投票
import React, { FC, useEffect } from 'react'
import { TypedDocumentNode } from '@apollo/client'
    interface UseCustomMutationInter {
      username: string,
      mutation: TypedDocumentNode
    }
    //honestly I prefere to separate that interface...
    const UseCustomMutation: FC<MutationProps> = ({mutation, username}) => {
      if (!mutation || !username) return null
      
      
      const [myFunc, {data, error}] = useMutation(mutation);

      useEffect(() => {
        myFunc({variables:{username}}) 
        console.log(data?.GetUser)
        console.log(`${error}`)
      }, [])
     return data //???? If you are creating a component, it is better to use a callBack to get its response and do what you need...

//I think in this case it's better to show an assembled component of mine since I don't know exactly its purpose... but I think your component has the wrong idea.
    }


///----- My code

import React, { FC } from 'react'
import { useMutation } from '@apollo/client'
import ConfirmToDoProps from './interface'
import GCButton from '@generics/GCButton'
import LoadingPage from '@generics/LoadingPage'
import { helperCloser } from '@utils'

const ConfirmToDo: FC<ConfirmToDoProps> = ({ schema }) => {
    if (!schema || !schema?.message || !schema?.txtBtnAct || !!schema?.mutation ) return null
    const { message, mutation, txtBtnAct, ...resVar } = schema
    const [mutationAct, { loading }] = useMutation(mutation, { ...(resVar || {}) })
    if (loading) return <LoadingPage vertCenter />
    return (
        <section className='w-100'>
            <p className='h-md-4 h6 mb-4'>{message}</p>
            <section className='w-100 text-right'>
                <GCButton
                    alternative
                    customClass='px-4 py-2 mr-3'
                    content={txtBtnAct}
                    onClick={mutationAct}
                />
                <GCButton
                    customClass='px-4 py-2'
                    content='Cancel'
                    onClick={helperCloser}
                />
            </section>
        </section>
    )
}

export default ConfirmToDo


import { TypedDocumentNode, MutationHookOptions, OperationVariables, ApolloError } from '@apollo/client'



//example of usage:

<ConfirmToDo
                schema={{
                    message,
                    mutation: MYMUTATION,
                    variables: { id },
                    txtBtnAct: 'Delete',
                    onError: (error: ApolloError) => handlePopup({
                        content: (
                            <GCMsg
                                message={`${error}`}
                                type='regular'
                                overTitle={`You can't perform this action.`}
                                iconName='fa-exclamation-triangle'
                                icoClass='text-danger'
                            />
                        )
                    }),
                    onCompleted: (data) => {
                        //do your stuff
                        console.log(data)
                    }
                }}
            />

interface SchemaInter {
    message: string
    txtBtnAct: string
    mutation: TypedDocumentNode
    variables: OperationVariables
    onCompleted: (data: MutationHookOptions | undefined) => Promise<void>
    onError: (error: ApolloError) => void
}

interface ConfirmToDoProps {
    schema: SchemaInter
}

    

export default ConfirmToDoProps
© www.soinside.com 2019 - 2024. All rights reserved.