File size: 1,705 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { useQuery } from '@tanstack/react-query';
import i18n from 'i18n-calypso';
import { Question, QuestionType } from 'calypso/components/survey-container/types';
import wpcom from 'calypso/lib/wp';

type SurveyStructureQueryArgs = {
	surveyKey: string;
};

type SurveyStructureResponse = {
	header_text: string;
	key: string;
	sub_header_text: string;
	type: string;
	options: {
		label: string;
		value: string;
		help_text: string;
		additional_props: Record< string, boolean >;
	}[];
}[];

const mapSurveyStructureResponse = ( response: SurveyStructureResponse ): Question[] =>
	response.map( ( question ) => {
		return {
			headerText: question.header_text,
			key: question.key,
			options: question.options.map( ( option ) => {
				return {
					label: option.label,
					value: option.value,
					helpText: option.help_text,
					additionalProps: option.additional_props,
				};
			} ),
			subHeaderText: question.sub_header_text,
			type: QuestionType[ question.type.toUpperCase() as keyof typeof QuestionType ],
		};
	} );

const useSurveyStructureQuery = ( { surveyKey }: SurveyStructureQueryArgs ) => {
	// This follows exact logic as addLocaleQueryParam() middleware
	// which will add _locale to the query param and we want to cache
	// our surveys with the same locale value.
	const locale = i18n.getLocaleVariant() || i18n.getLocaleSlug();
	const queryKey = [ 'survey-structure', surveyKey, ...( locale ? [ locale ] : [] ) ];

	return useQuery( {
		queryKey,
		queryFn: () => {
			return wpcom.req.get( {
				path: `/segmentation-survey/${ surveyKey }`,
				apiNamespace: 'wpcom/v2',
			} );
		},
		select: mapSurveyStructureResponse,
	} );
};

export default useSurveyStructureQuery;