-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathscriptProviderHooks.ts
More file actions
60 lines (53 loc) · 1.68 KB
/
scriptProviderHooks.ts
File metadata and controls
60 lines (53 loc) · 1.68 KB
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
import React, { useContext } from "react";
import { ScriptContext } from "../context/scriptProviderContext";
import {
validateReducer,
validateBraintreeAuthorizationData,
} from "./contextValidator";
import { SCRIPT_LOADING_STATE } from "../types";
import type {
ScriptContextDerivedState,
ScriptContextState,
ScriptReducerAction,
} from "../types";
/**
* Custom hook to get access to the Script context and
* dispatch actions to modify the state on the {@link ScriptProvider} component
*
* @returns a tuple containing the state of the context and
* a dispatch function to modify the state
*/
export function usePayPalScriptReducer(): [
ScriptContextDerivedState,
React.Dispatch<ScriptReducerAction>,
] {
const scriptContext = validateReducer(useContext(ScriptContext));
const derivedStatusContext = {
...scriptContext,
isInitial: scriptContext.loadingStatus === SCRIPT_LOADING_STATE.INITIAL,
isPending: scriptContext.loadingStatus === SCRIPT_LOADING_STATE.PENDING,
isResolved: scriptContext.loadingStatus === SCRIPT_LOADING_STATE.RESOLVED,
isRejected: scriptContext.loadingStatus === SCRIPT_LOADING_STATE.REJECTED,
};
return [
derivedStatusContext,
scriptContext.dispatch as React.Dispatch<ScriptReducerAction>,
];
}
/**
* Custom hook to get access to the ScriptProvider context
*
* @returns the latest state of the context
*/
export function useScriptProviderContext(): [
ScriptContextState,
React.Dispatch<ScriptReducerAction>,
] {
const scriptContext = validateBraintreeAuthorizationData(
validateReducer(useContext(ScriptContext)),
);
return [
scriptContext,
scriptContext.dispatch as React.Dispatch<ScriptReducerAction>,
];
}