PluginProbe
Parse.ly / 3.24.2
Parse.ly v3.24.2
3.24.3 3.24.2 3.24.1 3.24.0 3.23.7 3.23.6 3.23.5 3.23.4 3.23.3 3.16.0 3.16.1 3.16.2 3.16.3 3.16.4 3.17.0 3.18.0 3.18.1 3.19.0 3.19.1 3.19.2 3.19.3 3.2.0 3.2.1 3.20.0 3.20.1 All 107 releases
wp-parsely / src / blocks / recommendations / recommendations-store.tsx

recommendations-store.tsx in Parse.ly 3.24.2, at src/blocks/recommendations/recommendations-store.tsx

74 lines 2.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /**
2 * WordPress dependencies
3 */
4 import { createContext, useContext, useMemo, useReducer } from '@wordpress/element';
5
6 /**
7 * Internal dependencies
8 */
9 import { RecommendationsAction } from './constants';
10 import { Recommendation } from './models/Recommendation';
11
12 type RecommendationError = Error & { code: string|number, data?: { status?: string|number } };
13
14 interface RecommendationState {
15 isLoaded: boolean;
16 recommendations: Recommendation[];
17 uuid: string | null;
18 clientId: string | null;
19 error: RecommendationError | null;
20 }
21
22 // eslint-disable-next-line @typescript-eslint/no-explicit-any
23 const RecommendationsContext = createContext( {} as any );
24
25 // eslint-disable-next-line @typescript-eslint/no-explicit-any
26 const reducer = ( state: RecommendationState, action: any ): RecommendationState => {
27 switch ( action.type ) {
28 case RecommendationsAction.Error:
29 return { ...state, isLoaded: true, error: action.error, recommendations: [] };
30 case RecommendationsAction.Loaded:
31 return { ...state, isLoaded: true };
32 case RecommendationsAction.Recommendations: {
33 const { recommendations } = action;
34 if ( ! Array.isArray( recommendations ) ) {
35 return { ...state, recommendations: [] };
36 }
37 const validRecommendations = recommendations.map(
38 // eslint-disable-next-line camelcase
39 ( { title, url, image_url, thumb_url_medium } ) => ( {
40 title,
41 url,
42 image_url, // eslint-disable-line camelcase
43 thumb_url_medium, // eslint-disable-line camelcase
44 } )
45 );
46 return { ...state, isLoaded: true, error: null, recommendations: validRecommendations };
47 }
48 default:
49 return { ...state };
50 }
51 };
52
53 interface RecommendationStore {
54 clientId?: string;
55 children: React.ReactNode;
56 }
57
58 export const RecommendationsStore = ( props: RecommendationStore ) => {
59 const defaultState: RecommendationState = {
60 isLoaded: false,
61 recommendations: [],
62 uuid: window.PARSELY?.config?.uuid ?? null,
63 clientId: props?.clientId ?? null,
64 error: null,
65 };
66
67 const [ state, dispatch ] = useReducer( reducer, defaultState );
68 return useMemo( () => {
69 return <RecommendationsContext.Provider value={ { state, dispatch } } { ...props } />;
70 }, [ props, state ] );
71 };
72
73 export const useRecommendationsStore = () => useContext( RecommendationsContext );
74