Home > Mobile >  Is there a way to reset store to initialState after end of each module?
Is there a way to reset store to initialState after end of each module?

Time:11-28

I haven't implemented it yet but I have a counter state which counts for cycle of 3 rounds. After the first cycle, I want the counter to reset to 0 for another cycle.

Action.ts

export const readCounter = createAction(
    '[Cycle Counter] read cycle counter',
    props<{counter: Counter}> ()
);

This works perfectly for the first cycle i.e. 3 rounds

export interface Counter {
count: number
}

export const initialState: Counter = {
    count:0
};

export const indexReducer = ( state: any, action: any): Counter => {
    const reducer = createReducer(
        initialState,
        on(readCounter, (state, { counter }): any => (
            {
                count: counter.count
            }
        ))
        
        );
    return reducer(state, action);
};

So when I start the second cycle, the second cycle consists of 10 rounds, instead of starting from 1, it starts from 4 (continues with the 3).

I have the same logic but in different modules. My components are using the same store. I tried to use different counters, but getting errors. So after each cycle, and reset the redux devTool, it refreshes and it starts from 1 but i will lose the record on the first cycle.

CodePudding user response:

State is global, therefore you need different state properties for each module, with different actions.

export const readCounterModule1 = createAction(
    '[Cycle Counter] read cycle counter module 1',
    props<{count: number}> ()
);

export const readCounterModule2 = createAction(
    '[Cycle Counter] read cycle counter module 2',
    props<{count: number}> ()
);

export const initialState: Counter = {
    module1count: 0,
    module2count: 0
};

export const indexReducer = ( state: any, action: any): Counter => {
    const reducer = createReducer(
        initialState,
        on(readCounterModule1, (state, { count }): any => (
          {
            module1count: count
          }
        )),
        on(readCounterModule2, (state, { count }): any => (
          {
            module2count: count
          }
        ))
     );
    return reducer(state, action);
};

  • Related