File size: 1,188 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useCallback } from 'react';
import { DomainsApiError } from 'calypso/lib/domains/types';
import wp from 'calypso/lib/wp';
import { domainForwardingQueryKey } from './domain-forwarding-query-key';
import { DomainForwardingObject } from './use-domain-forwarding-query';

export default function useUpdateDomainForwardingMutation(
	domainName: string,
	queryOptions: {
		onSuccess?: () => void;
		onError?: ( error: DomainsApiError ) => void;
	}
) {
	const queryClient = useQueryClient();
	const mutation = useMutation( {
		mutationFn: ( forwarding: DomainForwardingObject ) =>
			wp.req.post( `/sites/all/domain/${ domainName }/redirects`, forwarding ),
		...queryOptions,
		onSuccess() {
			queryClient.invalidateQueries( { queryKey: domainForwardingQueryKey( domainName ) } );
			queryOptions.onSuccess?.();
		},
		onError( error: DomainsApiError ) {
			queryOptions.onError?.( error );
		},
	} );

	const { mutate } = mutation;

	const updateDomainForwarding = useCallback(
		( forwarding: DomainForwardingObject ) => mutate( forwarding ),
		[ mutate ]
	);

	return { updateDomainForwarding, ...mutation };
}