@applicaster/zapp-react-native-utils
Version:
Applicaster Zapp React Native utilities package
49 lines (37 loc) • 1.57 kB
text/typescript
/// <reference types="@applicaster/applicaster-types" />
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Context, useContext, useState } from "react";
import { ActionsContext } from "@applicaster/zapp-react-native-ui-components/Contexts/ActionsContext";
import { reactHooksLogger } from "../logger";
const logger = reactHooksLogger.addSubsystem("actions");
type ActionPlugin<T = unknown> = QuickBrickPlugin & { context: Context<T> };
type ActionContext<T = unknown> = Record<string, ActionPlugin<T>>;
type ActionContexts<T = unknown> = {
actions: Record<string, ActionContext<T>>;
};
/**
* React Hook to subscribe to the custom action context
* @param {*} plugId - subscribes to the context of that action plugin
* @return {*} - global action provider context or context for specific action plugin
*/
export function useActions<T = unknown>(plugId: string): any {
const [logged, setLogged] = useState(false);
const context = useContext<ActionContexts<T>>(ActionsContext);
const actionContext = context?.actions?.[plugId]?.module?.context;
if (plugId) {
if (!actionContext) {
if (!logged) {
logger.warning({
message: `useActions: Couldn't find an action for ${plugId} plugin`,
data: { actions: context?.actions },
});
setLogged(true);
}
return undefined;
}
// Disabling the rule as it's fine to have a conditional hook in this use case.
// eslint-disable-next-line react-hooks/rules-of-hooks
return useContext(actionContext);
}
return context;
}