like-gold
like-gold•8mo ago

Docs outdated?

Docs says I can create custom Http req this way:
import { useUpdate } from "@refinedev/core";

const { mutate } = useUpdate();

mutate({
resource: "posts",
id: 1,
variables: {
title: "New title",
},
meta: {
method: "put",
},
});
import { useUpdate } from "@refinedev/core";

const { mutate } = useUpdate();

mutate({
resource: "posts",
id: 1,
variables: {
title: "New title",
},
meta: {
method: "put",
},
});
and when I do the same, I get this TS error:
Argument of type '{ resource: string; id: number; meta: { method: string; }; }' is not assignable to parameter of type 'UpdateParams<BaseRecord, HttpError, {}>'.
Property 'values' is missing in type '{ resource: string; id: number; meta: { method: string; }; }' but required in type '{ resource: string; id: BaseKey; mutationMode?: MutationMode | undefined; undoableTimeout?: number | undefined; onCancel?: ((cancelMutation: () => void) => void) | undefined; ... 5 more ...; optimisticUpdateMap?: OptimisticUpdateMapType<...> | undefined; }'.ts(2345)
useUpdate.d.ts(28, 5): 'values' is declared here.

//CODE
const { mutate: getOtp } = useUpdate();
getOtp({
resource: "posts",
id: 1,
meta: {
method: "put",
},
});
Argument of type '{ resource: string; id: number; meta: { method: string; }; }' is not assignable to parameter of type 'UpdateParams<BaseRecord, HttpError, {}>'.
Property 'values' is missing in type '{ resource: string; id: number; meta: { method: string; }; }' but required in type '{ resource: string; id: BaseKey; mutationMode?: MutationMode | undefined; undoableTimeout?: number | undefined; onCancel?: ((cancelMutation: () => void) => void) | undefined; ... 5 more ...; optimisticUpdateMap?: OptimisticUpdateMapType<...> | undefined; }'.ts(2345)
useUpdate.d.ts(28, 5): 'values' is declared here.

//CODE
const { mutate: getOtp } = useUpdate();
getOtp({
resource: "posts",
id: 1,
meta: {
method: "put",
},
});
I'm using latest version of refine, I just upgraded it.
21 Replies
kapa.ai
kapa.ai•8mo ago
Hi @script4559. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- The TypeScript error you're encountering is due to the missing values property in the mutate function call. The values property is required when using the useUpdate hook in Refine. Here's how you should structure your mutate function call:
const { mutate } = useUpdate();

mutate({
resource: "posts",
id: 1,
values: {
title: "New title",
},
meta: {
method: "put",
},
});
const { mutate } = useUpdate();

mutate({
resource: "posts",
id: 1,
values: {
title: "New title",
},
meta: {
method: "put",
},
});
In this example, values is an object that contains the new data for the record you want to update. The resource and id properties specify the record to update, and the meta property allows you to customize the HTTP method used for the update request. You can find more information about the useUpdate hook and its parameters in the Refine documentation (https://refine.dev/docs/api-reference/core/hooks/data/useUpdate/). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai•8mo ago
<@584066183989428345> kapa.ai is still learning and improving, please let us know how it did by reacting below
like-gold
like-gold•8mo ago
@kapa.ai I am trying to create a custom request handler for a get request which shouldn't run on pageload but onClick of a button. How do I do that?
kapa.ai
kapa.ai•8mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- You can achieve this by using the useCustom hook from Refine. The useCustom hook allows you to make custom requests to your API. However, you need to be careful to follow the Rules of Hooks (https://reactjs.org/docs/hooks-rules.html) which state that hooks cannot be called inside callbacks or loops, they must be called at the top level of a React function component or a custom hook. Here's an example of how you can structure this:
import { useCustom, useApiUrl } from "@refinedev/core";
import { useState } from 'react';

function MyComponent() {
const apiUrl = useApiUrl();
const [buttonClicked, setButtonClicked] = useState(false);
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(false);

const { mutate } = useCustom({
url: `${apiUrl}/posts-unique-check`,
method: "get",
config: {
headers: {
"x-custom-header": "foo-bar",
},
query: {
title: "Foo bar",
},
},
});

const handleClick = async () => {
setIsLoading(true);
const response = await mutate();
setData(response);
setIsLoading(false);
}

return (
<button onClick={handleClick}>Click me</button>
);
}
import { useCustom, useApiUrl } from "@refinedev/core";
import { useState } from 'react';

function MyComponent() {
const apiUrl = useApiUrl();
const [buttonClicked, setButtonClicked] = useState(false);
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(false);

const { mutate } = useCustom({
url: `${apiUrl}/posts-unique-check`,
method: "get",
config: {
headers: {
"x-custom-header": "foo-bar",
},
query: {
title: "Foo bar",
},
},
});

const handleClick = async () => {
setIsLoading(true);
const response = await mutate();
setData(response);
setIsLoading(false);
}

return (
<button onClick={handleClick}>Click me</button>
);
}
In this example, when the button is clicked, the handleClick function is called. This function calls the mutate function returned by useCustom, which sends the request. The response from the request is then stored in the data state variable. Please note that the useCustom hook does not run on page load but only when the mutate function is called. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai•8mo ago
<@584066183989428345> kapa.ai is still learning and improving, please let us know how it did by reacting below
like-gold
like-gold•8mo ago
@kapa.ai i'm getting a Property 'mutate' does not exist on type 'QueryObserverResult<CustomResponse<BaseRecord>, HttpError> & UseLoadingOvertimeReturnType'. when I try to the mutate property
kapa.ai
kapa.ai•8mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message you're seeing suggests that the mutate property is not found on the object returned by the useCustom hook. This is likely because the useCustom hook does not return a mutate property. Instead, the useCustom hook returns a UseMutationResult object from the TanStack Query's useMutation function, as well as an overtime property. The UseMutationResult object does not have a mutate property. If you want to execute a mutation, you should use the mutate or mutateAsync methods from the UseMutationResult object. Here's an example:
const { mutate } = useMutation(myMutationFunction);
const { mutate } = useMutation(myMutationFunction);
In this example, myMutationFunction is the mutation function you want to execute. You can then call mutate to execute the mutation. You can find more information about the useMutation function in the React Query documentation (https://react-query.tanstack.com/reference/useMutation). If you're trying to use the mutate property with the useCustom hook in Refine, you might be misunderstanding how to use this hook. The useCustom hook is used for making custom requests to your API, and it does not return a mutate property. You can find more information about the useCustom hook in the Refine documentation (https://refine.dev/docs/api-reference/core/hooks/data/useCustom/). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai•8mo ago
<@584066183989428345> kapa.ai is still learning and improving, please let us know how it did by reacting below
like-gold
like-gold•8mo ago
@kapa.ai I discovered the useCustomMutation hook but it doesn't allow me to use get request is there any hook in the Refine docs that allow me to use mutate function for a get request?
kapa.ai
kapa.ai•8mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Refine does not provide a specific hook to use a GET request with a mutate function. The mutate function is typically used with mutation hooks like useCreate, useUpdate, and useDelete, which correspond to POST, PUT/PATCH, and DELETE HTTP methods respectively. For GET requests, Refine provides hooks like useGetList, useGetOne, useGetMany. These hooks are used to fetch data and don't have a mutate function because GET requests don't mutate data on the server. If you want to make a custom GET request upon an action (like a button click), you can use the useQuery hook from react-query which is already bundled with Refine. Here's an example:
import { useQuery } from 'react-query';
import axios from 'axios';

function MyComponent() {
const { isLoading, error, data } = useQuery('fetchData', () =>
axios.get('<https://api.example.com/data'>).then(res => res.data)
);

if (isLoading) return 'Loading...';
if (error) return 'An error has occurred: ' + error.message;

return (
<div>
{data.map(item => (
<div key={item.id}>{item.title}</div>
))}
</div>
);
}
import { useQuery } from 'react-query';
import axios from 'axios';

function MyComponent() {
const { isLoading, error, data } = useQuery('fetchData', () =>
axios.get('<https://api.example.com/data'>).then(res => res.data)
);

if (isLoading) return 'Loading...';
if (error) return 'An error has occurred: ' + error.message;

return (
<div>
{data.map(item => (
<div key={item.id}>{item.title}</div>
))}
</div>
);
}
In this example, useQuery is used to fetch data from an API when the component is rendered. The first argument to useQuery is a unique key for the query, and the second argument is a function that returns a promise which resolves to the data you want to fetch. You can find more information about useQuery in the React Query documentation (https://react-query.tanstack.com/reference/useQuery). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai•8mo ago
<@584066183989428345> kapa.ai is still learning and improving, please let us know how it did by reacting below
like-gold
like-gold•8mo ago
@kapa.ai what could have happened that would make my login state not to reflect in my refine app? I am using rest api and set up the data provider and authProvider but after login success, it still redirects me to the login page.
kapa.ai
kapa.ai•8mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- There could be several reasons why your login state is not reflecting in your Refine app. Here are a few possibilities: 1. Check Error in Auth Provider: Ensure that your authProvider is correctly set up and there are no errors in the login method. The login method should return a promise that resolves to { success: true } upon successful login. If there's an error, it should return { success: false, error: { message: 'Error message' } }. 2. Check Local Storage: If you're storing the authentication token in local storage, ensure that the token is being correctly set after login. If the token is not set or is cleared for some reason, the user will be redirected to the login page. 3. Check API Response: Ensure that your API is returning the correct response upon successful login. The response should include the necessary data to authenticate the user in subsequent requests. 4. Check Redirection Logic: Ensure that your redirection logic is correct. If you're using the useLogin hook from Refine, it will automatically redirect the user to the previous page or the root page upon successful login. If you're handling redirection manually, ensure that you're redirecting the user to the correct page. 5. Check Authorization: If your app uses role-based authorization, ensure that the user has the necessary permissions to access the page they're being redirected to. If the user doesn't have the necessary permissions, they might be redirected back to the login page. If you're still having trouble, you might find it helpful to refer to the Refine documentation (https://refine.dev/docs), particularly the sections on authentication (https://refine.dev/docs/advanced-tutorials/auth/auth0/#auth-provider) and authorization (https://refine.dev/docs/examples/auth-provider/auth0). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai•8mo ago
<@584066183989428345> kapa.ai is still learning and improving, please let us know how it did by reacting below
like-gold
like-gold•8mo ago
@kapa.ai after using my custom authProvider, when I login and its successful, the login state doesn't persist and I still get redirected back to the login page and not the authenticated pages. What could be happening
export const authProvider: AuthBindings = {
login: async ({ reference, passcode, providerName }) => {
try {
const { data } = await axiosInstance.get(
`${API_BASE_URL}/authentication/otp/verify`,
{
params: { passcode, reference },
}
);
localStorage.setItem("authToken", data.token);

return {
success: true,
redirectTo: "/",
};
} catch (error: any) {
console.error(error);
return {
success: false,
error: {
message: "message" in error ? error.message : "Login failed",
name: "Invalid OTP",
},
};
}
},
export const authProvider: AuthBindings = {
login: async ({ reference, passcode, providerName }) => {
try {
const { data } = await axiosInstance.get(
`${API_BASE_URL}/authentication/otp/verify`,
{
params: { passcode, reference },
}
);
localStorage.setItem("authToken", data.token);

return {
success: true,
redirectTo: "/",
};
} catch (error: any) {
console.error(error);
return {
success: false,
error: {
message: "message" in error ? error.message : "Login failed",
name: "Invalid OTP",
},
};
}
},
kapa.ai
kapa.ai•8mo ago
Let me check the knowledge base for you. One moment! :books: @script4559 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!
other-emerald
other-emerald•8mo ago
Hey @script4559, we've sent a fix to the docs about the wrong variable name in the example 🤦 About the auth provider, can you check and make sure your check method is returning authenticated: true after you logged in? 🤔 If this check out, can you try upgrading refine packages to latest versions? We had an update about the <Authenticated> components this week which resolves some other issues which can be related with the one you're facing.
like-gold
like-gold•8mo ago
nice the check method works, thanks When was the upgrade released though? I upgraded yesterday night. @aliemirs
other-emerald
other-emerald•8mo ago
No need for an update then, we had the releases on Monday 😅 Can you try to provide a reproducible example or a code sample? Are you using react router dom?
like-gold
like-gold•8mo ago
yes I am using react router dom. The issue has been resolved though if that's why you need a code sample
other-emerald
other-emerald•8mo ago
Oh, great! Have a nice day!