Andrew
Andrew

Reputation: 933

ngrx - how to perform an operation once a dispatched action has successfully updated the store?

I'm trying to implement an undo action in my Angular application where I'm using @ngrx/store. What I want to be able to do is dispatch the UNDO action, and then once the action has been handled, the data has been updated by the reducer and been pushed through the store, I want to do something with that updated data.

Here's how I'm currently trying to pull this off. Basically, because records$ comes from a BehaviorSubject, I will initially get a value on subscribe. Then I dispatch the action and wait for the update to come through. There has to be a better way, right?

undoRecords() {
    let count = 1;
    // The records$ observable comes from the ngrx store
    let obs = this.records$.take(2).subscribe(records => {
        if(count == 1) {
            this.store.dispatch({type: UNDO_RECORDS, payload: undefined}); // this will change the records 
            count++;
        }
        else {
            this.someService.doSomething(records);
        }
    });
}

Upvotes: 1

Views: 762

Answers (2)

Vamshi
Vamshi

Reputation: 9331

What I usually do is have three actions : ACTION, ACTION_SUCCESS, ACTION_ERROR .

ACTION triggers the actual action, along with change the status in store (inprogress=true) if you are interested to track the progress.

ACTION_SUCCESS , puts status 'inprogress' to false. And update the actual data.

You can monitor the the inprogress state and you will know when the task is done.

Upvotes: 1

George Metsis
George Metsis

Reputation: 107

Use npm package ngrx-undo.

 npm install --save ngrx-undo

in your AppModule:

import {handleUndo, configureBufferSize} from 'ngrx-undo';

// if you want to update the buffer (which defaults to 100)
configureBufferSize(150);

@NgModule({
    imports: [
        // pass the handleUndo in the metaReducers
        StoreModule.provideStore(rootReducer, {metaReducers: [handleUndo]}) 
    ]
})
export class AppModule { }

To undo an action, simply use the undo action creator.

import {undo} from "ngrx-undo";

// create an action
let action = {type: REMOVE_WINE, payload: {id: wine.id}};

// dispatch it
this.store.dispatch(action);

// undo the action
this.store.dispatch(undo(action));

Have a look here.

Upvotes: 0

Related Questions