deep-jade
deep-jade6mo ago

Need sample of useCustom hook

is there any sample how to use useCustom hook?
22 Replies
kapa.ai
kapa.ai6mo ago
Hi @yohan. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- Sure, here is a basic usage example of the useCustom hook from the Refine documentation:
import { useCustom, useApiUrl } from "@refinedev/core";

interface PostUniqueCheckResponse {
isAvailable: boolean;
}

const apiUrl = useApiUrl();

const { data, isLoading } = useCustom<PostUniqueCheckResponse>({
url: `${apiUrl}/posts-unique-check`,
method: "get",
config: {
headers: {
"x-custom-header": "foo-bar",
},
query: {
title: "Foo bar",
},
},
});
import { useCustom, useApiUrl } from "@refinedev/core";

interface PostUniqueCheckResponse {
isAvailable: boolean;
}

const apiUrl = useApiUrl();

const { data, isLoading } = useCustom<PostUniqueCheckResponse>({
url: `${apiUrl}/posts-unique-check`,
method: "get",
config: {
headers: {
"x-custom-header": "foo-bar",
},
query: {
title: "Foo bar",
},
},
});
In this example, useApiUrl is used to get the base URL of the API endpoint. The useCustom hook is then used to send a request to the endpoint. The useCustom hook expects a url, method, and config properties. The url property accepts the endpoint URL. The method property accepts the type of method of the endpoint (a "get" endpoint in this case). The config property accepts values like the headers for the endpoint, query parameters, and more. When properties are changed, the useCustom hook will trigger a new request. The response from the request can be accessed through the data property, and the loading state can be checked with the isLoading property. For more detailed information, you can refer to the useCustom documentation (https://refine.dev/docs/data/hooks/use-custom/). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@706071614717952071> kapa.ai is still learning and improving, please let us know how it did by reacting below
deep-jade
deep-jade6mo ago
can you give me sample how to trigger api call using useCustom when the button is clicked @kapa.ai can you give me sample how to trigger api call using useCustom when the button is clicked
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Sure, to trigger an API call using useCustom when a button is clicked, you can use the enabled option in queryOptions to control when the query runs. Here's an example:
import { useCustom, useApiUrl } from "@refinedev/core";
import { Button } from "antd";

interface PostUniqueCheckResponse {
isAvailable: boolean;
}

const apiUrl = useApiUrl();

const Component = () => {
const { data, isLoading, refetch } = useCustom<PostUniqueCheckResponse>({
url: `${apiUrl}/posts-unique-check`,
method: "get",
config: {
headers: {
"x-custom-header": "foo-bar",
},
query: {
title: "Foo bar",
},
},
queryOptions: {
enabled: false,
},
});

const handleClick = () => {
refetch();
};

return (
<Button onClick={handleClick}>Fetch Data</Button>
);
};
import { useCustom, useApiUrl } from "@refinedev/core";
import { Button } from "antd";

interface PostUniqueCheckResponse {
isAvailable: boolean;
}

const apiUrl = useApiUrl();

const Component = () => {
const { data, isLoading, refetch } = useCustom<PostUniqueCheckResponse>({
url: `${apiUrl}/posts-unique-check`,
method: "get",
config: {
headers: {
"x-custom-header": "foo-bar",
},
query: {
title: "Foo bar",
},
},
queryOptions: {
enabled: false,
},
});

const handleClick = () => {
refetch();
};

return (
<Button onClick={handleClick}>Fetch Data</Button>
);
};
In this example, useCustom is initially set with enabled: false to prevent the query from running immediately. When the button is clicked, the refetch function is called to trigger the query. Please note that this is a basic example and you might need to adjust it according to your needs. For more detailed information, you can refer to the useCustom documentation (https://refine.dev/docs/data/hooks/use-custom/). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@706071614717952071> kapa.ai is still learning and improving, please let us know how it did by reacting below
deep-jade
deep-jade6mo ago
@kapa.ai can you give example how to submit custom form using useCustom hook?
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Sure, here's an example of how you might use the useCustom hook to submit a form:
import { useCustom, useApiUrl } from "@refinedev/core";
import { Button, Form, Input } from "antd";

interface PostUniqueCheckResponse {
isAvailable: boolean;
}

const apiUrl = useApiUrl();

const Component = () => {
const { data, isLoading, refetch } = useCustom<PostUniqueCheckResponse>({
url: `${apiUrl}/posts-unique-check`,
method: "get",
config: {
headers: {
"x-custom-header": "foo-bar",
},
query: {
title: "Foo bar",
},
},
queryOptions: {
enabled: false,
},
});

const handleSubmit = (values) => {
refetch({
url: `${apiUrl}/posts-unique-check`,
method: "post",
config: {
body: JSON.stringify(values),
},
});
};

return (
<Form onFinish={handleSubmit}>
<Form.Item name="title">
<Input placeholder="Title" />
</Form.Item>
<Button type="primary" htmlType="submit">Submit</Button>
</Form>
);
};
import { useCustom, useApiUrl } from "@refinedev/core";
import { Button, Form, Input } from "antd";

interface PostUniqueCheckResponse {
isAvailable: boolean;
}

const apiUrl = useApiUrl();

const Component = () => {
const { data, isLoading, refetch } = useCustom<PostUniqueCheckResponse>({
url: `${apiUrl}/posts-unique-check`,
method: "get",
config: {
headers: {
"x-custom-header": "foo-bar",
},
query: {
title: "Foo bar",
},
},
queryOptions: {
enabled: false,
},
});

const handleSubmit = (values) => {
refetch({
url: `${apiUrl}/posts-unique-check`,
method: "post",
config: {
body: JSON.stringify(values),
},
});
};

return (
<Form onFinish={handleSubmit}>
<Form.Item name="title">
<Input placeholder="Title" />
</Form.Item>
<Button type="primary" htmlType="submit">Submit</Button>
</Form>
);
};
In this example, useCustom is initially set with enabled: false to prevent the query from running immediately. When the form is submitted, the refetch function is called with the new configuration to trigger the query. Please note that this is a basic example and you might need to adjust it according to your needs. For more detailed information, you can refer to the useCustom documentation (https://refine.dev/docs/data/hooks/use-custom/). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
deep-jade
deep-jade6mo ago
@kapa.ai I think for submitting form it's better to use useMutation instead of useCustom. Do you have sample how to use useMutation for submitting form when a button is clicked?
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Sure, here's an example of how you might use the useMutation hook to submit a form:
import { useMutation } from "@refinedev/core";
import { Button, Form, Input } from "antd";

const Component = () => {
const { mutate } = useMutation();

const handleSubmit = (values) => {
mutate({
resource: "posts",
type: "create",
variables: {
data: values,
},
});
};

return (
<Form onFinish={handleSubmit}>
<Form.Item name="title">
<Input placeholder="Title" />
</Form.Item>
<Button type="primary" htmlType="submit">Submit</Button>
</Form>
);
};
import { useMutation } from "@refinedev/core";
import { Button, Form, Input } from "antd";

const Component = () => {
const { mutate } = useMutation();

const handleSubmit = (values) => {
mutate({
resource: "posts",
type: "create",
variables: {
data: values,
},
});
};

return (
<Form onFinish={handleSubmit}>
<Form.Item name="title">
<Input placeholder="Title" />
</Form.Item>
<Button type="primary" htmlType="submit">Submit</Button>
</Form>
);
};
In this example, useMutation is used to create a mutation function (mutate). When the form is submitted, the handleSubmit function is called, which in turn calls the mutate function with the necessary parameters to create a new post. Please note that this is a basic example and you might need to adjust it according to your needs. For more detailed information, you can refer to the useMutation documentation (https://refine.dev/docs/data/hooks/use-mutation/). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@706071614717952071> kapa.ai is still learning and improving, please let us know how it did by reacting below
deep-jade
deep-jade6mo ago
@kapa.ai do you mean useCustomMutation instead of useMutation?
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Yes, you're correct. I apologize for the confusion. In the context of Refine, you should use useCustomMutation for custom mutation requests. Here's an example of how you might use the useCustomMutation hook to submit a form:
import { useCustomMutation, useApiUrl } from "@refinedev/core";
import { Button, Form, Input } from "antd";

interface ICategory {
id: number;
title: string;
}

const apiUrl = useApiUrl();

const Component = () => {
const { mutate } = useCustomMutation<ICategory>();

const handleSubmit = (values) => {
mutate({
url: `${apiUrl}/categories`,
method: "post",
values: values,
});
};

return (
<Form onFinish={handleSubmit}>
<Form.Item name="title">
<Input placeholder="Title" />
</Form.Item>
<Button type="primary" htmlType="submit">Submit</Button>
</Form>
);
};
import { useCustomMutation, useApiUrl } from "@refinedev/core";
import { Button, Form, Input } from "antd";

interface ICategory {
id: number;
title: string;
}

const apiUrl = useApiUrl();

const Component = () => {
const { mutate } = useCustomMutation<ICategory>();

const handleSubmit = (values) => {
mutate({
url: `${apiUrl}/categories`,
method: "post",
values: values,
});
};

return (
<Form onFinish={handleSubmit}>
<Form.Item name="title">
<Input placeholder="Title" />
</Form.Item>
<Button type="primary" htmlType="submit">Submit</Button>
</Form>
);
};
In this example, useCustomMutation is used to create a mutation function (mutate). When the form is submitted, the handleSubmit function is called, which in turn calls the mutate function with the necessary parameters to create a new category. Please note that this is a basic example and you might need to adjust it according to your needs. For more detailed information, you can refer to the useCustomMutation documentation (https://refine.dev/docs/data/hooks/use-custom-mutation). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@706071614717952071> kapa.ai is still learning and improving, please let us know how it did by reacting below
deep-jade
deep-jade6mo ago
@kapa.ai how to handle axios connection error?
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- To handle connection errors with Axios, you can use Axios interceptors. An interceptor allows you to run your code or modify the request or response before the request is sent or before Promise settles. Here's an example of how you might set up an interceptor to handle errors:
import axios, { AxiosRequestConfig } from "axios";
import { HttpError } from "@refinedev/core";

const axiosInstance = axios.create({
baseURL: "<http://127.0.0.1:5000/api",>
});

axiosInstance.interceptors.response.use(
(response) => {
return response;
},
(error) => {
const customError: HttpError = {
...error,
message: error.response?.data?.message,
statusCode: error.response?.status,
};

return Promise.reject(customError);
}
);

export { axiosInstance };
import axios, { AxiosRequestConfig } from "axios";
import { HttpError } from "@refinedev/core";

const axiosInstance = axios.create({
baseURL: "<http://127.0.0.1:5000/api",>
});

axiosInstance.interceptors.response.use(
(response) => {
return response;
},
(error) => {
const customError: HttpError = {
...error,
message: error.response?.data?.message,
statusCode: error.response?.status,
};

return Promise.reject(customError);
}
);

export { axiosInstance };
In this example, axios.create is used to create a new Axios instance. An interceptor is then added to the instance using axiosInstance.interceptors.response.use. The second function passed to use will be called when a request is rejected. In this function, the error is transformed into an HttpError and then rejected again. Please note that this is a basic example and you might need to adjust it according to your needs. For more detailed information, you can refer to the Refine documentation (https://refine.dev/docs/tutorial/understanding-dataprovider/create-dataprovider#error-handling) and Axios documentation (https://axios-http.com/docs/interceptors). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@706071614717952071> kapa.ai is still learning and improving, please let us know how it did by reacting below
deep-jade
deep-jade6mo ago
@kapa.ai how to display error notification when axios cannot connect to the API service?
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- To display an error notification when Axios cannot connect to the API service, you can use Refine's notification system. Refine provides a built-in notification provider that you can use to display notifications. Here's an example of how you might set this up:
import axios from "axios";
import { DataProvider, HttpError, useNotification } from "@refinedev/core";

// Error handling with axios interceptors
const axiosInstance = axios.create();

const { notify } = useNotification();

axiosInstance.interceptors.response.use(
(response) => {
return response;
},
(error) => {
const customError: HttpError = {
...error,
message: error.response?.data?.message,
statusCode: error.response?.status,
};

notify({
type: "error",
message: customError.message,
});

return Promise.reject(customError);
},
);
import axios from "axios";
import { DataProvider, HttpError, useNotification } from "@refinedev/core";

// Error handling with axios interceptors
const axiosInstance = axios.create();

const { notify } = useNotification();

axiosInstance.interceptors.response.use(
(response) => {
return response;
},
(error) => {
const customError: HttpError = {
...error,
message: error.response?.data?.message,
statusCode: error.response?.status,
};

notify({
type: "error",
message: customError.message,
});

return Promise.reject(customError);
},
);
In this example, useNotification is used to get the notify function. When an error occurs, the notify function is called with an object that specifies the type of notification and the message to display. Please note that this is a basic example and you might need to adjust it according to your needs. For more detailed information, you can refer to the Refine documentation (https://refine.dev/docs/notification/notification-provider) and Axios documentation (https://axios-http.com/docs/interceptors). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@706071614717952071> kapa.ai is still learning and improving, please let us know how it did by reacting below
deep-jade
deep-jade6mo ago
@kapa.ai how to update fields error message based on server response after I submit data using useCustomMutation?
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- To update field error messages based on server response after submitting data using useCustomMutation, you can use the onError callback in the useForm hook from Ant Design. Here's an example:
import { useCustomMutation } from "@refinedev/core";
import { Form, Input, Button } from "antd";

const Component = () => {
const { mutate } = useCustomMutation();
const [form] = Form.useForm();

const handleSubmit = (values) => {
mutate({
url: "/your-endpoint",
method: "post",
values: values,
}).catch((error) => {
// Assuming error.response.data is an object like { fieldName: "Error message" }
const fieldErrors = Object.entries(error.response.data).map(([name, errors]) => ({
name,
errors: Array.isArray(errors) ? errors : [errors],
}));

form.setFields(fieldErrors);
});
};

return (
<Form form={form} onFinish={handleSubmit}>
<Form.Item name="fieldName">
<Input placeholder="Field Name" />
</Form.Item>
<Button type="primary" htmlType="submit">Submit</Button>
</Form>
);
};
import { useCustomMutation } from "@refinedev/core";
import { Form, Input, Button } from "antd";

const Component = () => {
const { mutate } = useCustomMutation();
const [form] = Form.useForm();

const handleSubmit = (values) => {
mutate({
url: "/your-endpoint",
method: "post",
values: values,
}).catch((error) => {
// Assuming error.response.data is an object like { fieldName: "Error message" }
const fieldErrors = Object.entries(error.response.data).map(([name, errors]) => ({
name,
errors: Array.isArray(errors) ? errors : [errors],
}));

form.setFields(fieldErrors);
});
};

return (
<Form form={form} onFinish={handleSubmit}>
<Form.Item name="fieldName">
<Input placeholder="Field Name" />
</Form.Item>
<Button type="primary" htmlType="submit">Submit</Button>
</Form>
);
};
In this example, useCustomMutation is used to create a mutation function (mutate). When the form is submitted, the handleSubmit function is called, which in turn calls the mutate function with the necessary parameters. If the mutation fails (i.e., the promise is rejected), the catch block is executed. In this block, the error messages are extracted from the server response and set on the corresponding fields using form.setFields. Please note that this is a basic example and you might need to adjust it according to your needs and the structure of your server's error response. For more detailed information, you can refer to the useCustomMutation documentation (https://refine.dev/docs/data/hooks/use-custom-mutation) and Ant Design's Form documentation (https://ant.design/components/form/). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@706071614717952071> kapa.ai is still learning and improving, please let us know how it did by reacting below