Add better state management utilizing Redux

This commit is contained in:
Daniel Dudzic 2024-09-10 12:03:50 +02:00
parent db449b5d70
commit bccfe4c436
No known key found for this signature in database
GPG key ID: 31B40D33E3465483
11 changed files with 432 additions and 172 deletions

View file

@ -0,0 +1,59 @@
// File: axoStore.js
import { createReduxStore, register, dispatch } from '@wordpress/data';
export const STORE_NAME = 'woocommerce-paypal-payments/axo-block';
// Initial state
const DEFAULT_STATE = {
isGuest: true,
isAxoActive: false,
};
// Actions
const actions = {
setIsGuest: ( isGuest ) => ( {
type: 'SET_IS_GUEST',
payload: isGuest,
} ),
setIsAxoActive: ( isAxoActive ) => ( {
type: 'SET_IS_AXO_ACTIVE',
payload: isAxoActive,
} ),
};
// Reducer
const reducer = ( state = DEFAULT_STATE, action ) => {
switch ( action.type ) {
case 'SET_IS_GUEST':
return { ...state, isGuest: action.payload };
case 'SET_IS_AXO_ACTIVE':
return { ...state, isAxoActive: action.payload };
default:
return state;
}
};
// Selectors
const selectors = {
getIsGuest: ( state ) => state.isGuest,
getIsAxoActive: ( state ) => state.isAxoActive,
};
// Create and register the store
const store = createReduxStore( STORE_NAME, {
reducer,
actions,
selectors,
} );
register( store );
// Utility functions
export const setIsGuest = ( isGuest ) => {
try {
dispatch( STORE_NAME ).setIsGuest( isGuest );
} catch ( error ) {
console.error( 'Error updating isGuest state:', error );
}
};