/
context.tsx
84 lines (73 loc) · 2.23 KB
/
context.tsx
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
83
84
/**
* External dependencies
*/
import React, { createContext, useState, useCallback, useContext } from 'react';
import apiFetch from '@wordpress/api-fetch';
import { useDispatch } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import { NAMESPACE } from 'data/constants';
import type { OverviewSurveyFields } from './types';
type ResponseStatus = 'pending' | 'resolved' | 'error';
const useContextValue = ( initialState: OverviewSurveyFields = {} ) => {
const [ surveySubmitted, setSurveySubmitted ] = useState( false );
const [ responseStatus, setResponseStatus ] = useState< ResponseStatus >(
'resolved'
);
const [ surveyAnswers, setSurveyAnswers ] = useState( initialState );
const { createErrorNotice } = useDispatch( 'core/notices' );
const submitSurvey = useCallback(
async ( answers: OverviewSurveyFields ) => {
setResponseStatus( 'pending' );
try {
await apiFetch( {
path: `${ NAMESPACE }/survey/payments-overview`,
method: 'POST',
data: answers,
} );
setSurveySubmitted( true );
setResponseStatus( 'resolved' );
} catch ( e ) {
setResponseStatus( 'error' );
setSurveySubmitted( false );
createErrorNotice(
__(
'An error occurred while submitting the survey. Please try again.',
'woocommerce-payments'
)
);
}
},
[ setResponseStatus, setSurveySubmitted, createErrorNotice ]
);
return {
setSurveySubmitted: submitSurvey,
responseStatus,
surveySubmitted,
surveyAnswers,
setSurveyAnswers,
};
};
type ContextValue = ReturnType< typeof useContextValue >;
const WcPayOverviewSurveyContext = createContext< ContextValue | null >( null );
export const WcPayOverviewSurveyContextProvider: React.FC< {
initialData?: OverviewSurveyFields;
} > = ( { children, initialData } ) => {
return (
<WcPayOverviewSurveyContext.Provider
value={ useContextValue( initialData ) }
>
{ children }
</WcPayOverviewSurveyContext.Provider>
);
};
export const useOverviewSurveyContext = (): ContextValue => {
const context = useContext( WcPayOverviewSurveyContext );
if ( ! context ) {
throw new Error( 'An error occurred when using survey context' );
}
return context;
};
export default WcPayOverviewSurveyContext;