According to Moo, it seems that the built-in function onNgrxForms()
only checks the top level of the state, requiring a custom implementation for deeper inspection.
In my own experience, I encountered a similar challenge when tasked with creating virtual tabs that could be independently stored and displayed.
I ended up devising two implementations: one straightforward approach capable of checking a two-level state (currently utilized in my production project) and a more generic solution that works recursively.
This code is inspired by the ngrx-forms implementation of onNgrxForms()
. For specific details, refer to the links below:
https://github.com/MrWolfZ/ngrx-forms/blob/master/src/reducer.ts
https://github.com/MrWolfZ/ngrx-forms/blob/master/src/state.ts
State
export interface MyObject {
property: string;
}
export interface MyObjectFormValue {
property: string;
}
export interface Substate {
data: MyObject;
form: FormGroupState<MyObjectFormValue>;
}
export interface State {
[id: number]: Substate;
commonData1: any[];
commonData2: boolean;
}
The State
interface includes various Substates
containing FormGroupState
. While these can be accessed through an indexer, your implementation may solely rely on the field data
.
If desired, you can incorporate shared common data (such as fields commonData1
and commonData2
) among the Substates
.
Straightforward Approach
import { ALL_NGRX_FORMS_ACTION_TYPES, formStateReducer } from 'ngrx-forms';
function isSubstate(object: any): object is Substate {
return (
Boolean(object) &&
Object.prototype.hasOwnProperty.call(object, 'data') &&
Object.prototype.hasOwnProperty.call(object, 'form')
);
}
// Rest of the straightforward approach omitted for brevity
A simple method utilizing Object.entries
is applied due to the potentially unknown nature of Substates
within the State
. Direct access is possible if predefined keys are in place.
Generic Approach
// Generic approach using immer library
// Relevant functionality provided within this section
This version leverages the immer
library for immutable state updates.
It's worth noting that the function isFormState
isn't part of the library's public API, hence manual inclusion was required. Additionally, the introduction of a set visits
helps prevent issues related to circular references, while isObject
aids in filtering out certain properties during verification.