deep-jade
deep-jade5mo ago

graphql mutation

I am trying to use useForm from
import { useForm } from "@refinedev/react-hook-form";
import { useForm } from "@refinedev/react-hook-form";
i want to do both fetch and mutation using graphql how can i do it?
16 Replies
kapa.ai
kapa.ai5mo ago
Hi @Alex YT. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- You can use the useForm hook from @refinedev/react-hook-form to handle both fetching and mutation of data in your forms. The hook internally uses other hooks like useOne, useUpdate, and useCreate to handle data fetching and mutation logic for you. For GraphQL, you can use the @refinedev/nestjs-query package. On initial render, the useForm hook will make a getOne query to your API to get the initial values of the form. It will automatically detect the gqlMutation, extract selected fields from it and make a getOne query to your API. Here is an example of how you can use it:
import { useForm } from "@refinedev/react-hook-form";
import { GetFields, GetFieldsFromList } from "@refinedev/nestjs-query";
import { PostEditMutation } from "src/graphql/types";
import { POST_EDIT_MUTATION } from "./queries";

const { formProps } = useForm<GetFields<PostEditMutation>>({
meta: { gqlMutation: POST_EDIT_MUTATION },
});
import { useForm } from "@refinedev/react-hook-form";
import { GetFields, GetFieldsFromList } from "@refinedev/nestjs-query";
import { PostEditMutation } from "src/graphql/types";
import { POST_EDIT_MUTATION } from "./queries";

const { formProps } = useForm<GetFields<PostEditMutation>>({
meta: { gqlMutation: POST_EDIT_MUTATION },
});
If you want to customize the getOne query, you can also pass a gqlQuery field to the meta object:
const POST_EDIT_QUERY = gql`
query PostEdit($id: ID!) {
blogPost(id: $id) {
id
title
status
category {
id
title
}
categoryId
content
}
}
`;

const { formProps } = useForm<GetFields<PostEditMutation>>({
meta: {
gqlMutation: POST_EDIT_MUTATION,
gqlQuery: POST_EDIT_QUERY,
},
});
const POST_EDIT_QUERY = gql`
query PostEdit($id: ID!) {
blogPost(id: $id) {
id
title
status
category {
id
title
}
categoryId
content
}
}
`;

const { formProps } = useForm<GetFields<PostEditMutation>>({
meta: {
gqlMutation: POST_EDIT_MUTATION,
gqlQuery: POST_EDIT_QUERY,
},
});
For more detailed information, you can refer to the Refine Documentation (https://refine.dev/docs/data/packages/nestjs-query#usage-with-graphql-tag). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5mo ago
<@398749213795680259> kapa.ai is still learning and improving, please let us know how it did by reacting below
deep-jade
deep-jade5mo ago
@kapa.ai i am using gql-query-builder
kapa.ai
kapa.ai5mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- If you're using gql-query-builder with Refine, you can create dynamic queries and mutations for your needs. The useForm hook can be used in conjunction with these queries and mutations. Here's a general example of how you can use useForm with GraphQL:
import { useForm } from "@refinedev/core";
import gql from "graphql-tag";

const UPDATE_PRODUCT_MUTATION = gql`
mutation UpdateOneProduct($id: ID!, $input: UpdateOneProductInput!) {
updateOneProduct(id: $id, input: $input) {
id
title
category {
title
}
}
}
`;

const { formProps, saveButtonProps, queryResult } = useForm({
resource: "products",
id: 1,
meta: {
gqlMutation: UPDATE_PRODUCT_MUTATION,
},
});
import { useForm } from "@refinedev/core";
import gql from "graphql-tag";

const UPDATE_PRODUCT_MUTATION = gql`
mutation UpdateOneProduct($id: ID!, $input: UpdateOneProductInput!) {
updateOneProduct(id: $id, input: $input) {
id
title
category {
title
}
}
}
`;

const { formProps, saveButtonProps, queryResult } = useForm({
resource: "products",
id: 1,
meta: {
gqlMutation: UPDATE_PRODUCT_MUTATION,
},
});
In this example, useForm is used to handle the form logic. The gqlMutation field in the meta object is used to pass the GraphQL mutation to the useForm hook. When the form is submitted, the useForm hook will use this mutation to update the product. Please note that the gqlMutation field is not yet supported by the GraphQL data provider in Refine. However, it's planned to be added in the future (source (https://refine.dev/docs/data/packages/graphql)). For more detailed information, you can refer to the Refine Documentation (https://refine.dev/docs/guides-concepts/data-fetching#graphql). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5mo ago
<@398749213795680259> kapa.ai is still learning and improving, please let us know how it did by reacting below
deep-jade
deep-jade5mo ago
@kapa.ai how do i work with this kind of request
... on UpdateAdminSuccess {
admin {
... on Admin {
id
}
}
}
... on UpdateAdminValidationFailed {
message
fields {
... on UpdateAdminValidationFields {
id
name
}
}
}
... on UpdateAdminSuccess {
admin {
... on Admin {
id
}
}
}
... on UpdateAdminValidationFailed {
message
fields {
... on UpdateAdminValidationFields {
id
name
}
}
}
kapa.ai
kapa.ai5mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The request you've shared appears to be a part of a GraphQL mutation response that uses inline fragments to handle different types of responses. In GraphQL, the ... on syntax is used for inline fragments, which allow you to access fields that belong to certain types of objects within a union or interface. In your case, it seems like the mutation can return either a UpdateAdminSuccess or UpdateAdminValidationFailed type. If the mutation is successful, it returns an admin object with an id. If the mutation fails validation, it returns a message and fields object with id and name. To work with this in your application, you would typically check the type of the response and handle each case accordingly. Here's a general example:
const { data, loading, error } = useMutation(YOUR_MUTATION);

if (loading) {
return <div>Loading...</div>;
}

if (error) {
return <div>Error: {error.message}</div>;
}

if (data) {
if ('admin' in data) {
// Handle success case
console.log('Success, admin id:', data.admin.id);
} else if ('message' in data) {
// Handle validation failed case
console.log('Validation failed:', data.message, 'Fields:', data.fields);
}
}

// Render your component
const { data, loading, error } = useMutation(YOUR_MUTATION);

if (loading) {
return <div>Loading...</div>;
}

if (error) {
return <div>Error: {error.message}</div>;
}

if (data) {
if ('admin' in data) {
// Handle success case
console.log('Success, admin id:', data.admin.id);
} else if ('message' in data) {
// Handle validation failed case
console.log('Validation failed:', data.message, 'Fields:', data.fields);
}
}

// Render your component
Please note that this is a general example and might need to be adjusted based on your actual GraphQL mutation and the structure of your data. For more detailed information on working with GraphQL in Refine, you can refer to the Refine Documentation (https://refine.dev/docs/guides-concepts/data-fetching#graphql). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5mo ago
<@398749213795680259> kapa.ai is still learning and improving, please let us know how it did by reacting below
deep-jade
deep-jade5mo ago
@kapa.ai can you give me example using @refinedev/graphql
kapa.ai
kapa.ai5mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Sure, here's an example of how you can use the @refinedev/graphql package with Refine: First, you need to create a GraphQL client with your API URL and pass it to the dataProvider function to create a data provider:
import Refine from "@refinedev/core";
import dataProvider, { GraphQLClient } from "@refinedev/graphql";

const client = new GraphQLClient("<https://api.example.com/graphql">);

const App = () => (
<Refine
dataProvider={dataProvider(client)}
>
{/* ... */}
</Refine>
);
import Refine from "@refinedev/core";
import dataProvider, { GraphQLClient } from "@refinedev/graphql";

const client = new GraphQLClient("<https://api.example.com/graphql">);

const App = () => (
<Refine
dataProvider={dataProvider(client)}
>
{/* ... */}
</Refine>
);
(Source: Refine Documentation (https://refine.dev/docs/data/packages/graphql#usage)) If you want to enable realtime features of Refine, you can use the liveProvider:
import Refine from "@refinedev/core";
import dataProvider, { GraphQLClient, liveProvider, graphqlWS } from "@refinedev/graphql";

const client = new GraphQLClient("<https://api.example.com/graphql">);
const wsClient = graphqlWS.createClient({ url: "wss://api.example.com/graphql" });

const App = () => (
<Refine
dataProvider={dataProvider(client)}
liveProvider={liveProvider(wsClient)}
options={{ liveMode: "auto" }}
>
{/* ... */}
</Refine>
);
import Refine from "@refinedev/core";
import dataProvider, { GraphQLClient, liveProvider, graphqlWS } from "@refinedev/graphql";

const client = new GraphQLClient("<https://api.example.com/graphql">);
const wsClient = graphqlWS.createClient({ url: "wss://api.example.com/graphql" });

const App = () => (
<Refine
dataProvider={dataProvider(client)}
liveProvider={liveProvider(wsClient)}
options={{ liveMode: "auto" }}
>
{/* ... */}
</Refine>
);
(Source: Refine Documentation (https://refine.dev/docs/data/packages/graphql#usage)) For handling GraphQL mutations, you can use the useMutation hook from Refine. However, the specific usage would depend on the structure of your mutation and the data you're working with. The documentation does not provide a specific example for this, but you can refer to the Refine Documentation (https://refine.dev/docs/guides-concepts/data-fetching#graphql) for more information on working with GraphQL in Refine. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5mo ago
<@398749213795680259> kapa.ai is still learning and improving, please let us know how it did by reacting below
deep-jade
deep-jade5mo ago
@kapa.ai can you give me example using the above mentioned for a crude operation?
kapa.ai
kapa.ai5mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Sure, here's an example of how you can use the @refinedev/graphql package with Refine for CRUD operations: First, you need to create a GraphQL client with your API URL and pass it to the dataProvider function to create a data provider:
import Refine from "@refinedev/core";
import dataProvider, { GraphQLClient } from "@refinedev/graphql";

const client = new GraphQLClient("<https://api.example.com/graphql">);

const App = () => (
<Refine
dataProvider={dataProvider(client)}
>
{/* ... */}
</Refine>
);
import Refine from "@refinedev/core";
import dataProvider, { GraphQLClient } from "@refinedev/graphql";

const client = new GraphQLClient("<https://api.example.com/graphql">);

const App = () => (
<Refine
dataProvider={dataProvider(client)}
>
{/* ... */}
</Refine>
);
(Source: Refine Documentation (https://refine.dev/docs/data/packages/graphql#usage)) For CRUD operations, you can use the useGetList, useGetOne, useCreate, useUpdate, and useDelete hooks from Refine. Here's an example of how you can use these hooks:
import { useGetList, useGetOne, useCreate, useUpdate, useDelete } from "@refinedev/core";

// Fetch a list of resources
const { data, isLoading } = useGetList("posts");

// Fetch a single resource
const { data: postData, isLoading: postLoading } = useGetOne("posts", "1");

// Create a new resource
const { mutate: createPost } = useCreate("posts");
// You can then call createPost({ title: "New Post", content: "Hello, world!" }) to create a new post

// Update a resource
const { mutate: updatePost } = useUpdate("posts");
// You can then call updatePost({ id: "1", title: "Updated Post", content: "Hello, world!" }) to update a post

// Delete a resource
const { mutate: deletePost } = useDelete("posts");
// You can then call deletePost("1") to delete a post
import { useGetList, useGetOne, useCreate, useUpdate, useDelete } from "@refinedev/core";

// Fetch a list of resources
const { data, isLoading } = useGetList("posts");

// Fetch a single resource
const { data: postData, isLoading: postLoading } = useGetOne("posts", "1");

// Create a new resource
const { mutate: createPost } = useCreate("posts");
// You can then call createPost({ title: "New Post", content: "Hello, world!" }) to create a new post

// Update a resource
const { mutate: updatePost } = useUpdate("posts");
// You can then call updatePost({ id: "1", title: "Updated Post", content: "Hello, world!" }) to update a post

// Delete a resource
const { mutate: deletePost } = useDelete("posts");
// You can then call deletePost("1") to delete a post
Please note that these are general examples and might need to be adjusted based on your actual GraphQL schema and the structure of your data. For more detailed information on working with GraphQL in Refine, you can refer to the Refine Documentation (https://refine.dev/docs/guides-concepts/data-fetching#graphql). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5mo ago
<@398749213795680259> kapa.ai is still learning and improving, please let us know how it did by reacting below
deep-jade
deep-jade5mo ago
@kapa.ai this are my two schema using gql how do i do it? const GET_ADMIN = __typename ... on QueryAdminSuccess { admin { ... on Admin { id name role state } } } ; const UPDATE_ADMIN = ... on UpdateAdminSuccess { admin { ... on Admin { id } } } ... on UpdateAdminValidationFailed { message fields { ... on UpdateAdminValidationFields { id name } } } ;
kapa.ai
kapa.ai5mo ago
Let me check the knowledge base for you. One moment! :books: @Alex YT That's a great question, but unfortunately I am only capable of responding to a maximum of five questions per thread. Don't hesitate to create a new thread for any further questions you have though. I'm here to help!