-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathuseSetPassword.ts
67 lines (62 loc) · 1.85 KB
/
useSetPassword.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import {
OnError,
OnSuccess,
useAuthProvider,
useNotify,
useRedirect,
} from 'ra-core';
import { useMutation, UseMutationResult } from '@tanstack/react-query';
import { SetPasswordParams, SupabaseAuthProvider } from './authProvider';
/**
* This hook returns a function to call in order to set a user password on Supabase.
*
* @example
* import { useSupabaseAccessToken } from 'ra-supabase-core';
*
* const SetPasswordPage = () => {
* const access_token = useSupabaseAccessToken();
* const setPassword = useSetPassword();
*
* const handleSubmit = event => {
* setPassword({
* access_token,
* password: event.currentTarget.elements.password.value,
* });
* };
*
* return (
* <form onSubmit={handleSubmit}>
* <label for="password">Choose a password:</label>
* <input id="password" name="password" type="password" />
* <button type="submit">Save</button>
* </form>
* );
* };
**/
export const useSetPassword = (
options?: UseSetPasswordOptions
): [
UseMutationResult<unknown, Error, SetPasswordParams>['mutate'],
UseMutationResult<unknown, Error, SetPasswordParams>
] => {
const notify = useNotify();
const redirect = useRedirect();
const authProvider = useAuthProvider<SupabaseAuthProvider>();
const {
onSuccess = () => redirect('/'),
onError = error => notify(error.message, { type: 'error' }),
} = options || {};
const mutation = useMutation<unknown, Error, SetPasswordParams>({
mutationFn: params => {
return authProvider.setPassword(params);
},
onSuccess,
onError,
retry: false,
});
return [mutation.mutate, mutation];
};
export type UseSetPasswordOptions = {
onSuccess?: OnSuccess;
onError?: OnError;
};