@@ -3,7 +3,7 @@ import { setAxiosToken } from 'api/axiosInstances';
33import userAPI from 'api/userAPI' ;
44import { AxiosError } from 'axios' ;
55import { useSetNotification } from 'hooks/useSetNotification' ;
6- import { LoginFormType , LoginResponse } from 'models/apiTypes' ;
6+ import { LoginFormType , LoginResponse , ChangePasswordFormType , ChangePasswordResponse } from 'models/apiTypes' ;
77import { resetNotifications } from 'providers/Notifications/actions' ;
88import { useNotifications } from 'providers/Notifications/NotificationProvider' ;
99import { useMutation } from 'react-query' ;
@@ -42,3 +42,39 @@ export const useSignIn = () => {
4242 }
4343 ) ;
4444} ;
45+
46+ export const useChangePassword = ( ) => {
47+ const history = useHistory ( ) ;
48+ const setNotification = useSetNotification ( ) ;
49+ const [ , notificationDispatch ] = useNotifications ( ) ;
50+
51+ return useMutation < ChangePasswordResponse , AxiosError , ChangePasswordFormType > (
52+ ( params ) => {
53+ const { request } = userAPI . single . changePassword ( {
54+ old_password : params . old_password ,
55+ new_password1 : params . new_password1 ,
56+ new_password2 : params . new_password2 ,
57+ } ) ;
58+ return request ( ) ;
59+ } ,
60+ {
61+ onSuccess : async ( data ) => {
62+ notificationDispatch ( resetNotifications ( ) ) ;
63+ setAxiosToken ( data ?. token ?? '' ) ;
64+
65+ // change token in either local or session
66+ // based on weather remember me was checked during login or not
67+ (
68+ localStorage . getItem ( __TOKEN__ ) ? localStorage : sessionStorage
69+ ) . setItem ( __TOKEN__ , data ?. token ?? '' ) ;
70+
71+ setNotification ( 'Password changed.' , 'success' ) ;
72+ history . replace ( urls . settings ( ) ) ;
73+ } ,
74+ onError : ( errors ) => {
75+ setNotification ( 'Invalid credential combination.' , 'error' ) ;
76+ console . log ( errors ) ;
77+ } ,
78+ }
79+ ) ;
80+ } ;
0 commit comments