Observe Store
The observeStore
function allows developers to subscribe to a specific part of the Redux store and receive updates when that part changes. It functions similarly to the useGlobalStore
hook, but is designed to be used in vanilla JavaScript, making it more flexible for different environments.
public observeStore(
getterFunction: Function,
onChange: Function,
equalityFunction: Function = isStoreEqual
)
observeStore
is available in fdk-store >= v2.0.32
and fdk-store-gql >= v3.0.20
Parameters
getterFunction
A function that receives the Redux store state and returns a slice of the state that you are interested in subscribing to. You can either define your own function or use one from fpi.getters
, which provides pre-defined getter functions for common store slices.
Example:
const myGetter = window.fpi.getters.USER_DATA;
onChange
A callback function that will be triggered whenever the state returned by getterFunction
changes. The new state will be passed as an argument to this function.
Example:
const handleUserChange = (newUserState) => {
console.log('User state updated:', newUserState);
};
equalityFunction
(Optional)
A function that takes two arguments (previousState
, currentState
) and compares them to determine if the state has changed. By default, the function uses isStoreEqual
, which can be customized if needed.
Example:
const shallowEqual = (prev, curr) => prev.id === curr.id;
Returns: unsubscribe
A function to unsubscribe from the store updates. Call this when you no longer need to observe changes to the state.
Example
// Subscribing to the user slice of the store using fpi.getters
const unsubscribe = fpi.observeStore(
// Getter function from fpi.getters
fpi.getters.USER_DATA,
// onChange function
(newUserState) => { console.log('User state changed:', newUserState); },
// Optional custom equality check
(prevUser, currUser) => prevUser.id === currUser.id,
);
// Later when you want to unsubscribe:
unsubscribe();