import { useCallback } from 'react' ; import { useSWRConfig } from 'swr' ; import { User } from 'types/User' ; import usePost from '../_rest/usePost' ; import { getUserCacheKey , useAuthenticatedUser } from './useUser' ; type RemoveUserAddressRequest = { addresses : string [ ] ; } ; type RemoveUserAddressResponse = { success : boolean ; } ; export default function useRemoveUserAddress ( ) { const user = useAuthenticatedUser ( ) ; const removeUserAddress = usePost ( ) ; const { mutate } = useSWRConfig ( ) ; return useCallback ( async ( addressToRemove ) => { await removeUserAddress < RemoveUserAddressResponse , RemoveUserAddressRequest > ( '/users/update/addresses/remove' , 'remove user address' , { addresses : [ addressToRemove ] } ) ; await mutate ( getUserCacheKey ( { username : user . username } ) , ( user ) => { const addresses = user . addresses . filter ( ( address ) => address !== addressToRemove ) ; return { ... user , addresses } ; } , false ) ; await mutate ( getUserCacheKey ( { id : user . id } ) , ( user ) => { const addresses = user . addresses . filter ( ( address ) => address !== addressToRemove ) ; return { ... user , addresses } ; } , false ) ; } , [ mutate , removeUserAddress , user . id , user . username ] ) ; }