| 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 |
|