-
Notifications
You must be signed in to change notification settings - Fork 10.7k
/
useCampaigns.ts
82 lines (73 loc) · 1.88 KB
/
useCampaigns.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* External dependencies
*/
import { useSelect } from '@wordpress/data';
/**
* Internal dependencies
*/
import { Campaign } from '~/marketing/types';
import { STORE_KEY } from '~/marketing/data-multichannel/constants';
import {
CampaignsState,
Campaign as APICampaign,
ApiFetchError,
} from '~/marketing/data-multichannel/types';
import { useRegisteredChannels } from '~/marketing/hooks';
type UseCampaignsType = {
loading: boolean;
data?: Array< Campaign >;
error?: ApiFetchError;
meta?: {
total?: number;
};
};
/**
* Custom hook to get campaigns.
*
* @param page Page number. Default is `1`.
* @param perPage Page size, i.e. number of records in one page. Default is `5`.
*/
export const useCampaigns = ( page = 1, perPage = 5 ): UseCampaignsType => {
const { data: channels } = useRegisteredChannels();
return useSelect(
( select ) => {
const { hasFinishedResolution, getCampaigns } = select( STORE_KEY );
const campaignsState = getCampaigns< CampaignsState >(
page,
perPage
);
const convert = ( campaign: APICampaign ): Campaign => {
const channel = channels?.find(
( el ) => el.slug === campaign.channel
);
return {
id: `${ campaign.channel }|${ campaign.id }`,
title: campaign.title,
description: '',
cost: `${ campaign.cost.currency } ${ campaign.cost.value }`,
manageUrl: campaign.manage_url,
icon: channel?.icon || '',
channelName: channel?.title || '',
channelSlug: campaign.channel,
};
};
const error =
campaignsState.pages && campaignsState.pages[ page ]?.error;
const data =
campaignsState.pages &&
campaignsState.pages[ page ]?.data?.map( convert );
return {
loading: ! hasFinishedResolution( 'getCampaigns', [
page,
perPage,
] ),
data,
error,
meta: {
total: campaignsState.total,
},
};
},
[ page, perPage ]
);
};