Within my Angular application, I am currently implementing a state management system using BehaviourSubject
This is what I have in my store file:
myStoreData = new BehaviourSubject([])
In my actions file, I have the following:
export const SAVE_DATA_IN_CONTEXT = '[User] Save user the incoming data';
Therefore, in the component, when necessary, the method to invoke is as follows:
click(newData){
this.reducerService('SAVE_DATA_IN_CONTEXT' , newData)
}
My goal is to ensure that the data sent to the store (BehaviourSubject) does not replace the existing data but appends it to it:
The desired outcome should be:
Data to send to BehaviourSubject (array) = existing data (array of objects) + new data (object)
This is how my reducer looks, and here is what I have tried:
public dispatchAction(actionTag: string, newDataPayload: any | null): void {
switch (actionTag) {
case ActionsTags.SAVE_DATA_IN_CONTEXT :
const newDataToSet = [...Stores.myStoreData.getValue() , ...newDataPayload ];
Stores.myStoreData.next(newDataPayload);
break;
}
I believe that using the getValue() method is not ideal, and I want to avoid using Stores.myStoreData.subscribe()
due to potential unsubscription issues and repetitive subscriptions from the user click method.
I am seeking a better way to handle this process effectively, such as potentially changing the BehaviourSubject implementation.
Any suggestions?