Intercepting filter/sort/column "model" changes / transactions - ag-grid

I would like to control the grid's sorting, filtering, and column states with an external store. Ideally I want to intercept the filterChanged and sortChanged events, emit them to the store, and let the store update the grid programmatically using the grid API.
readonly GRID_CONFIG: GridOptions = {
onSortChanged: (event: SortChangedEvent) => {
// Tell store that the sort changed
this.sortChanged.emit(this.grid.api.getSortModel());
},
onFilterChanged: (event: FilterChangedEvent) => {
// Tell store that the filter changed
this.filterChanged.emit(this.grid.api.getFilterModel());
},
onFilterModified: (event: FilterModifiedEvent) => {
// This isn't useful because it only relates to the floating filters pre-apply...
}
}
Unfortunately, once the onFilterChanged and onSortChanged events are called, the grid has already been updated, so the updates from the store are redundant.
The closest thing to what I want is isApplyServerSideTransaction, as this callback allows cancelling the transaction.
isApplyServerSideTransaction: (params: IsApplyServerSideTransactionParams) => {
// Emit model changes to the store so that the store can update the grid
this.sortChanged.emit(this.grid.api.getSortModel());
this.filterChanged.emit(this.grid.api.getFilterModel());
// Do not update the grid (redundant)
return false;
}
However, this is only supported for Server Side Row Model Full mode. This callback is never fired in my case, since I am using partial mode.
Are there any other tricks for hooking into the model changes before they're applied, or is this just not supported?
Update: I'm specifically trying to intercept the UI-triggered changes to the sort/filter model. I know this can be achieved with custom filters (and maybe custom headers?) but I'd much rather leverage Ag-Grid's built-in UI than build a whole custom copy, just to intercept one event.

Since you are using Server-side Row Model, the getRows callback is fired whenever the Grid is requesting data, i.e. whenever you filter/sort/group etc. So if you want to intercept what is being returned to the Grid, you should do it inside the getRows callback.

Related

Avoiding repetitive calls when creating reactfire hooks

When initializing a component using reactfire, each time I add a reactfire hook (e.g. useFirestoreDocData), it triggers a re-render and therefore repeats all previous initialization. For example:
const MyComponent = props => {
console.log(1);
const firestore = useFirestore();
console.log(2);
const ref = firestore.doc('count/counter');
console.log(3);
const { value } = useFirestoreDocDataOnce(ref);
console.log(4);
...
return <span>{value}</span>;
};
will output:
1
1
2
3
1
2
3
4
This seems wasteful, is there a way to avoid this?
This is particularly problematic when I need the result of one reactfire hook to create another (e.g. retrieve data from one document to determine which other document to read) and it duplicates the server calls.
See React's documentation of Suspense.
Particulary that part: Approach 3: Render-as-You-Fetch (using Suspense)
Reactfire uses this mechanics. It is not supposed to fetch more than one time for each call even if the line is executed more than once. The mechanics behind "understand" that the fetch is already done and will start the next one.
In your case, react try to render your component, see it needs to fetch, stop rendering and show suspense's fallback while fetching. When fetch is done it retry to render your component and as the fetch is completed it will render completely.
You can confirm in your network tab that each calls is done only once.
I hope I'm clear, please don't hesitate to ask for more details if i'm not.

Wait for backend service response before making changes to ag-grid table

I am using ag-grid/ag-grid-angular to provide an editable grid of data backed by a database. When a user edits a cell I want to be able to post the update to the backend service and if the request is successful update the grid and if not undo the user's changes and show an error.
I have approached this problem from a couple different angles but have yet to find the solution that meets all my requirements and am also curious about what the best practice would be to implement this kind of functionality.
My first thought was to leverage the cellValueChanged event. With this approach I can see the old and new values and then make a call to my service to update the database. If the request is successful then everything is great and works as expected. However, if the request fails for some reason then I need to be able to undo the user's changes. Since I have access to the old value I can easily do something like event.node.setDataValue(event.column, event.oldValue) to revert the user's changes. However, since I am updating the grid again this actually triggers the cellValueChanged event a second time. I have no way of knowing that this is the result of undoing the user's changes so I unnecessarily make a call to my service again to update the data even though the original request was never successful in updating the data.
I have also tried using a custom cell editor to get in between when the user is finished editing a cell and when the grid is actually updated. However, it appears that there is no way to integrate an async method in any of these classes to be able to wait for a response from the server to decide whether or not to actually apply the user's changes. E.g.
isCancelBeforeStart(): boolean {
this.service.updateData(event.data).subscribe(() => {
return false;
}, error => {
return true;
});
}
does not work because this method is synchronous and I need to be able to wait for a response from my service before deciding whether to cancel the edit or not.
Is there something I am missing or not taking in to account? Or another way to approach this problem to get my intended functionality? I realize this could be handled much easier with dedicated edit/save buttons but I am ideally looking for an interactive grid that is saving the changes to the backend as the user is making changes and providing feedback in cases where something went wrong.
Any help/feedback is greatly appreciated!
I understand what you are trying to do, and I think that the best approach is going to be to use a "valueSetter" function on each of your editable columns.
With a valueSetter, the grid's value will not be directly updated - you will have to update your bound data to have it reflected in the grid.
When the valueSetter is called by the grid at the end of the edit, you'll probably want to record the original value somehow, update your bound data (so that the grid will reflect the change), and then kick off the back-end save, and return immediately from the valueSetter function.
(It's important to return immediately from the valueSetter function to keep the grid responsive. Since the valueSetter call from the grid is synchronous, if you try to wait for the server response, you're going to lock up the grid while you're waiting.)
Then, if the back-end update succeeds, there's nothing to do, and if it fails, you can update your bound data to reflect the original value.
With this method, you won't have the problem of listening for the cellValueChanged event.
The one issue that you might have to deal with is what to do if the user changes the cell value, and then changes it again before the first back-end save returns.
onCellValueChanged: (event) => {
if (event.oldValue === event.newValue) {
return;
}
try {
// apiUpdate(event.data)
}
catch {
event.node.data[event.colDef.Field] = event.oldValue;
event.node.setDataValue(event.column, event.oldValue);
}
}
By changing the value back on node.data first, when setDataValue() triggers the change event again, oldValue and newValue are actually the same now and the function returns, avoiding the rather slow infinite loop.
I think it's because you change the data behind the scenes directly without agGrid noticing with node.data = , then make a change that agGrid recognises and rerenders the cell by calling setDataValue. Thereby tricking agGrid into behaving.
I would suggest a slightly better approach than StangerString, but to credit him the idea came from his approach. Rather than using a test of the oldValue/newValue and allowing the event to be called twice, you can go around the change detection by doing the following.
event.node.data[event.colDef.field] = event.oldValue;
event.api.refreshCells({ rowNodes: [event.node], columns: [event.column.colId] });
What that does is sets the data directly in the data store used by aggrid, then you tell it to refresh that grid. That will prevent the onCellValueChanged event from having to be called again.
(if you arent using colIds you can use the field or pass the whole column, I think any of them work)

Specman- How can I implement a sequential coverage?

I have an event named tx_intrpt_e.
I want to create the following coverage:
On tx_intrpt_e wait few cycles cross uarttx_dma_sreq==1.
Where uarttx_dma_sreq is a port of the interface.
You can define a new event that emitted "few cycles" after the original one, and the define the cover on the new event:
event tx_intrpt_e;
event tx_intrpt_e_delay is {#tx_intrpt_e;[3]}#clk;
cover tx_intrpt_e_delay is {
item uarttx_dma_sreq using ignore uarttx_dma_sreq==0;
}

Observable that wraps FromEventPattern while caching the most recent event for new subscribers

I have created an observable by using Observable.FromEventPattern. Let's call it fromEvents.
I want to create another observable that wraps fromEvents. We'll call this 2nd observable wrapper.
When wrapper is subscribed to it should:
Publish the most recent item from fromEvents if any.
Publish the rest of items coming from fromEvents
Obviously wrapper will need to maintain a subscription to fromEvents so that it always has access to the most recent event.
I have tried various combinations of Replay, Publish, PublishLast, Observable.Defer and I'm never quite getting the results I'm looking for.
I'm certain Rx has operators that will meet my needs, I'm just unsure of exactly how to put everything together, being the newb that I am.
I think I've been able to get what I want by doing this:
Events = Observable.FromEventPattern(...).Replay(1).RefCount();
// contrived example
// in my real app the subscription lives for a specific duration
// and Events is exposed as a readonly property
using(Events.Subscribe())
{
// get most recent or wait for first
var e = Events.FirstAsync().Wait();
}
Example using the Publish overload that uses a BehaviorSubject behind the scenes to keep track of the most recent event.
var fromEvents = Observable.FromEventPattern(...);
var published = fromEvents.Publish(null);
// subscribe to this one
var wrapper = published.Where(e => e != null);
// start collecting values
var subscription = published.Connect();
wrapper.Subscribe(...);

How to correctly saving the viewmodel of page to handle tombstoning

I'm building a WP7 app, and I'm now at the point of handling the tombstoning part of it.
What I am doing is saving the viewmodel of the page in the Page.State bag when the NavigatedFrom event occurs, and reading it back in the NavigatedTo (with some check to detect whether I should read from the bag or read from the real live data of the application).
First my VM was just a wrapper to the domain model
public string Nome
{
get
{
return _dm.Nome;
}
set
{
if (value != _dm.Nome)
{
_dm.Nome= value;
NotifyPropertyChanged("Nome");
}
}
}
But this didn't always work because when saving to the bag and then reading back, the domain model was not deserialized correctly.
Then I changed my VM implementation to be just a copy of the properties I needed from the DM:
public string Nome
{
get
{
return _nome;
}
set
{
if (value !=nome)
{
_nome= value;
NotifyPropertyChanged("Nome");
}
}
}
and with the constructor that does:
_nome = dm.Nome;
And now it works, but I was not sure if this is the right approach.
Thx
Simone
Any transient state information should be persisted in the Application.Deactivated event and then restored in the Application.Activated event for tombstoning support.
If you need to store anything between application sessions then you could use the Application.Closing event, but depending on what you need to store, you could just store it whenever it changes. Again, depending on what you need to store, you can either restore it in the Application.Launching event, or just read it when you need it.
The approach that you take depends entirely on your application's requirements and the method and location that you store your data is also up to you (binary serialization to isolated storage is generally accepted is being the fastest).
I don't know the details of your application, but saving and restoring data in NavigatedFrom/NavigatedTo is unlikely to be the right place to do it if you are looking to implement support for tombstoning.
I'd recommend against making a copy of part of the model as when tombstoning you'd (probably) need to persist both the full (app level) model and the page level copy when handling tombstoning.
Again the most appropriate solution will depend on the complexity of your application and the models it uses.
Application.Activated/Deactivated is a good place to handle tombstoning.
See why OnNavigatedTo/From may not be appropriate for your needs here.
How to correctly handle application deactivation and reactivation - Peter Torr's Blog
Execution Model Overview for Windows Phone