Created
October 7, 2020 17:32
-
-
Save dkotov/3503f19d132b2b8c75800a594407e13b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useMutation, queryCache } from 'react-query'; | |
import { useLocation, useHistory } from 'react-router-dom'; | |
import { UserStatus, api, showSuccessMessage } from 'package'; | |
const SuccessMessageByStatus = { | |
[UserStatus.BLOCKED]: 'User blocked', | |
[UserStatus.PROMOTED]: 'User promoted', | |
[UserStatus.ACTIVE]: 'User activated', | |
}; | |
function invalidateCache() { | |
queryCache.invalidateQueries('users'); | |
} | |
export function useUpdateUser(userId) { | |
return useMutation( | |
(data) => api.updateById(userId, data), | |
{ | |
onSuccess: invalidateCache, | |
}, | |
); | |
} | |
export function useUploadUserPhoto(userId) { | |
return useMutation( | |
(data) => api.uploadPhotoById(userId, data), | |
{ | |
onSuccess: invalidateCache, | |
}, | |
); | |
} | |
function useUpdateUserStatus(userId, status) { | |
const location = useLocation(); | |
const history = useHistory(); | |
return useMutation( | |
() => api.updateUserStatusById(userId, { status }), | |
{ | |
onSuccess: () => { | |
showSuccessMessage(SuccessMessageByStatus[status]); | |
if (status === UserStatus.BLOCKED && location.pathname !== 'users') { | |
history.replace('users'); | |
} | |
invalidateCache(); | |
}, | |
}, | |
); | |
} | |
export function useActivateUser(userId) { | |
return useUpdateUserStatus(userId, UserStatus.ACTIVE); | |
} | |
export function useBlockUser(userId) { | |
return useUpdateUserStatus(userId, UserStatus.BLOCKED); | |
} | |
export function usePromoteUser(userId) { | |
return useUpdateUserStatus(userId, UserStatus.PROMOTED); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment