AgGridReact stop editing and restore old value - reactjs

I have a react component with an AgGridReact which has an editable column. I want inside the onCellValueChanged event to check if the new value meets some conditions, and if not stop and restore the old value.
I've read that there is an api stopEditing:
https://www.ag-grid.com/documentation/javascript/cell-editing/#editing-api
Here it says:
"stopEditing(cancel): If the grid is editing then editing is stopped. Passing cancel=true will keep the cell's original value and passing cancel=false will take the latest value from the cell editor."
So I've tried using it. Just to test it out I did like this:
const onGridReady = params =>
{
gridApi.current = params.api;
}
const onCellValueChanged = async (event) =>
{
gridApi.current.stopEditing(true);
return;
}
I expected that every time I'll try to edit, no matter what, as soon as I click enter to finish editing, the old value will be restored but it just keeps the new value. The event itself is set properly and it is being invoked.
What am I doing wrong here? And if it's not the way to restore the previous value, what is?

stopEditing is called on the gridApi. By calling stopEditing in your onCellValueChanged, it's too late, the value has already changed.
Here's what you can do instead:
Use a valueSetter for your column. This way, you can accept only certain values and reject all others. For example, this valueSetter will only update the value if the newly entered value is "accept":
function myValuSetter(params) {
if (params.newValue != "accept") {
return false;
}
params.data.make = params.newValue
return true;
}
Demo.

Related

Showing the new row in react-table on the current page

I have been playing with ReactTable v7 for a while and have encountered the following problem: when the table is sorted and uses paginator sometimes adding (or editing) a row causes it to be outside the current page.
You can see the problem here:
https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/material-UI-kitchen-sink
Sort the table by First Name
Press add
Enter a record with First Name "zzzzz"
The record is added but is currently hidden which confuses users.
Is there a "standard" way to fix the issue? Am I missing something?
In v6 I have done a workaround for it:
React.useEffect(() => {
if (editedElementId && reactTable) {
const { data } = reactTable.props;
if (data && data.length > 0) {
const internal = reactTable.getResolvedState();
let position = -1;
internal.sortedData.forEach((row, i) => {
if (row._original.id === editedElementId) position = i;
});
if (position >= 0) {
const pageNumber = Math.floor(position / pageSize);
setPage(pageNumber);
} else {
alert.info("Element not visible");
}
}
}
}, [editedElementId]);
...
<ReactTable
ref={(r) => {setReactTable(r);}}
...
But maybe there is a bulit-in way to achieve it?
There is not currently a way to only sort the elements which are currently being displayed, no.
React Table v7's useSortBy hook sorts the entirety of the input data array, so sorting by First Name descending (A->Z) naturally places 'ZZZZZZ' at the end of the list, which will be hidden due to pagination. The v7 way of doing it would probably be similar to what you are doing already, using the exposed properties from the useTable hook instead of reactTable.resolvedState() and etc. Another way to do it would be to write your own custom sortBy method and only sort the items [0...n] where n is the number of currently displayed items.
As a side note, since the autoResetSortBy property is true by default in the example you linked, the step of sorting on First Name is irrelevant -- since the function which adds a new user to the list mutates the data array, the sorting method is reset. That function appends the new user to the end of the list, so it will always be on a new page, even if the "Rows per page" option is set to "All". Both issues can be fixed by setting autoResetSortBy to false, and changing the pageSize in addUserHandler.

Angular FormControl's material-checkboxes.component has selected values but this.controlValue is an empty array

I have an Angular form I've built that consists of a single material-checkboxes component. I have two copies of this component, one is static and one is dynamic. The only difference is that the dynamic version gets its control values from an API call. Both of these examples have one or more options defaulted as checked when the controls initialize.
The issue I have is that the dynamic one's model is out of sync with its view as long as its left unchanged (ie, if I don't click on any of the checkbox controls to select or unselect them). Once I click on one of the checkboxes, the model updates to sync with the view.
I can tell this because I can submit the static version and get expected results (the defaulted items are posted as values as expected). However, when I submit the dynamic one, I get an empty post.
Here is what the component looks like with the defaulted values before I submit it to see the submitted form data:
And here is the resulted submitted values (as expected):
By way of comparison, here is the same control (material-checkboxes.component.ts) but built using an external datasource to feed in the titleMap and also has defaulted values.
And here is the result after submit of the above form:
So, as the screencaps indicate, The manually created one works as expected and submits the form containing the defaulted values. However, the component with the dynamically generated values, even though the view shows it to have selected default options, submits as EMPTY.
Expected: this.controlValue = ['12', 'd4']
Actual:
onInit > this.controlValue = ['12', 'd4']
After updateValue method > this.controlValue = undefined // But the view is unchanged from the init
However, I can get it to submit data as expected, if I manually change any of the values, even if i set them exactly as they were defaulted. Its as if the form data is not being set until manually clicking on the options.
Here is a snippet from the template that holds the component:
<mat-checkbox
type="checkbox"
[class.mat-checkboxes-invalid]="showError && touched"
[class.mat-checkbox-readonly]="options?.readonly"
[checked]="allChecked"
[disabled]="(controlDisabled$ | async) || options?.readonly"
[color]="options?.color || 'primary'"
[indeterminate]="someChecked"
[name]="options?.name"
(focusout)="onFocusOut()"
(change)="updateAllValues($event)"
[required]="required"
[value]="controlValue">
Update: I found that the issue was that the form control's value is not updated before leaving the syncCurrentValues() method called just after the setTitleMap hostlistener. Adding a call to this.updateValue() in syncCurrentValues() resolves it and the model and view are back in sync. However, there is a problem, but first, here is the code that resolves the issue when there is a default value set in the this.options data:
#HostListener('document:setTitleMap', ['$event'])
setTitleMap(event: CustomEvent) {
if (event.detail.eventName === this.options.wruxDynamicHook && isRequester(this.componentId, event.detail.params)) {
this.checkboxList = buildTitleMap(event.detail.titleMap, this.options.enum, true, true, this.options.allowUnselect || false);
// Data coming in after ngInit. So if this is the first time the list is provided, then use the defaultValues from the options.
const value = this.setDefaultValueComplete ?
this.jsf.getFormControl(this)?.value || [] :
[].concat(this.options?.defaultValue || []);
this.syncCurrentValues(value);
// Set flag to true so we ignore future calls and not overwrite potential user edits
this.setDefaultValueComplete = true;
}
}
updateValue(event: any = {}) {
this.options.showErrors = true;
// this.jsf.updateArrayCheckboxList(this, this.options.readonly ? this.checkboxListInitValues : this.checkboxList);
this.jsf.updateArrayCheckboxList(this, this.checkboxList);
this.onCustomAction(this.checkboxList);
this.onCustomEvent(this.checkboxList);
this.jsf.forceUpdates();
if (this.jsf.mode === 'builder-properties') {
this.jsf.elementBlurred();
}
}
syncCurrentValues(newValues: Array<any>): void {
for (const checkboxItem of this.checkboxList) {
checkboxItem.checked = newValues.includes(checkboxItem.value);
}
this.updateValue(); // Fixed it. Otherwise, the checked items in titlemap never get synced to the model
}
The call to updateData() above fixes the issue in that case. However, when there are no default values in the options data and the checkbox data is loaded externally from an API call that executes after the ngOnInit has fired, I have the same issue. this.controlValue is empty after ngOnInit despite that the view has updated to show checked checkboxes. The model has made that happen through the setTitleMap() method but the controlValue still logs as an empty array.

setValue in a whole form with react-hook-form

I'm building up a user profile that has some addresses, the user can edit them, it's almost finished, but I'm stuck in setting the user edit address in a form.
Just like it shows in the GIF when I click the button no value is set, I'm using react-hook-form to build these forms.
This is the function that execute when I click on the button:
const editAddress = (i) => {
const addressClicked = addressList[i];
console.log(addressWatch());
setAddressValue("name", addressClicked);
setShowForm(true);
};
addressList is an array that is being looped, and then I get the key from the .map(v,i) and it returns an object with all the information that should populate the input fields for the user to edit it.
So, in the docs there is a function that is called "reset" that actually does exactly what I wanted, it wipes the current data from the form and it can replace with a new object data.
https://react-hook-form.com/api/useform/reset
The function looks like this now
const editAddress = (i) => {
const addressClicked = addressList[i];
addressReset(addressClicked);
setShowForm(true);
};

Get current value of Animated.Value, React-native

I'm trying to animate View with interpolate. I'd like to get a current value of my Animated.Value, but don't know how. I didn't understand how to do it with React-native docs.
this.state = {
translateAnim: new Animated.Value(0)
}
DeviceEventEmitter.addListener('Accelerometer', function (data) {
console.log(this.state.translateAnim);
// returns an object, but I need a value in current moment
}
I find out, how to get a value:
this.state.translateAnim.addListener(({value}) => this._value = value);
EDIT
to log a value I do the following:
console.log(this.state.translateAnim._value)
This also works for me...
const headerHeight = new Animated.Value(0);
After some manipulation....
console.log(headerHeight.__getValue())
It feels hackish but it gets the job done...
For the people with typescript.
console.log((this.state.translateAnim as any)._value);
It worked for me to full tsc as any.
Number.parseInt(JSON.stringify(translateAnim))
It works on React Hook
edit: CAUTION - MAY CAUSE SEVERE PERFORMANCE ISSUES. I have not been able to figure out why, but if you use this for 30+ simultaneous animations your framerate will slow to a crawl. It seems like it must be a bug in react-native with Animated.Value addListener as I don't see anything wrong with my code, it only sets a listener which sets a ref which should be instantaneous.
Here's a hook I came up with to do it without resorting to accessing private internal values.
/**
* Since there's no (official) way to read an Animated.Value synchronously this is the best solution I could come up with
* to have access to an up-to-date copy of the latest value without sacrificing performance.
*
* #param animatedValue the Animated.Value to track
* #param initial Optional initial value if you know it to initialize the latest value ref before the animated value listener fires for the first time
*
* returns a ref with the latest value of the Animated.Value and a boolean ref indicating if a value has been received yet
*/
const useAnimatedLatestValueRef = (animatedValue: Animated.Value, initial?: number) => {
//If we're given an initial value then we can pretend we've received a value from the listener already
const latestValueRef = useRef(initial ?? 0)
const initialized = useRef(typeof initial == "number")
useEffect(() => {
const id = animatedValue.addListener((v) => {
//Store the latest animated value
latestValueRef.current = v.value
//Indicate that we've recieved a value
initialized.current = true
})
//Return a deregister function to clean up
return () => animatedValue.removeListener(id)
//Note that the behavior here isn't 100% correct if the animatedValue changes -- the returned ref
//may refer to the previous animatedValue's latest value until the new listener returns a value
}, [animatedValue])
return [latestValueRef, initialized] as const
}
It seems like private property. But works for me. Helpful for debugging, but wouldn't recommend using it in production.
translateAnim._value
I actually found another way to get the value (not sure if it is a recommended way, but it works).
Use JSON.stringify() on the animated value and use Number on the result to convert it into Number.
E.g,
const animatedVal = new Animated.Value(0);
const jsanimated = JSON.stringify(animatedVal);
const finalResult = Number(jsanimated)

ExtJS: Added grid rows wont de-highlight

When adding a rows to a grid, and then clicking on it, it gets selected (and highlighted). Then, clicking elsewhere but the new row remains highlighted (so now there are to highlighted rows).
Please, does anyone know what the problem could be? How to make it behave normally, i.e. clicking a row deselects (de-highlights) the other one?
After I reload the page (so the new row is not new anymore), everything works as expected.
Edit: Here's the code for adding rows:
var rec = new store.recordType({
test: 'test'
});
store.add(rec);
Edit 2: The problem seems to be listful: true. If false, it works! But I need it to be true so I'm looking at this further... It looks like as if the IDs went somehow wrong... If the ID would change (I first create the record and then the server returns proper ID, that would also confuse the row selector, no?)
(Note, correct as ExtJS 3.3.1)
First of all, this is my quick and dirty hack. Coincidentally I have my CheckboxSelectionModel extended in my system:-
Kore.ux.grid.CheckboxSelectionModel = Ext.extend(Ext.grid.CheckboxSelectionModel, {
clearSelections : function(fast){
if(this.isLocked()){
return;
}
if(fast !== true){
var ds = this.grid.store,
s = this.selections;
s.each(function(r){
//Hack, ds.indexOfId(r.id) is not correct.
//Inherited problem from Store.reader.realize function
this.deselectRow(ds.indexOf(r));
//this.deselectRow(ds.indexOfId(r.id));
}, this);
s.clear();
}else{
this.selections.clear();
}
this.last = false;
}
});
And this is the place where the clearSelections fails. They try to deselect rows by using ds.indexOfId(r.id) and it will returns -1 because we do not have the index defined remapped.
And this is why we can't find the id:-
http://imageshack.us/photo/my-images/864/ssstore.gif/
Note that the first item in the image is not properly "remapped". This is because we have a problem in the "reMap" function in our Ext.data.Store, read as follow:-
// remap record ids in MixedCollection after records have been realized. #see Store#onCreateRecords, #see DataReader#realize
reMap : function(record) {
if (Ext.isArray(record)) {
for (var i = 0, len = record.length; i < len; i++) {
this.reMap(record[i]);
}
} else {
delete this.data.map[record._phid];
this.data.map[record.id] = record;
var index = this.data.keys.indexOf(record._phid);
this.data.keys.splice(index, 1, record.id);
delete record._phid;
}
}
Apparently, this method fails to get fired (or buggy). Traced further up, this method is called by Ext.data.Store.onCreateRecords
....
this.reader.realize(rs, data);
this.reMap(rs);
....
It does look fine on the first look, but when I trace rs and data, these data magically set to undefined after this.reader.realize function, and hence reMap could not map the phantom record back to the normal record.
I don't know what is wrong with this function, and I don't know how should I overwrite this function in my JsonReader. If any of you happen to be free, do help us trace up further for the culprit that causes this problem
Cheers
Lionel
Looks like to have multi select enabled for you grid. You can configure the selection model of the grid by using the Ext.grid.RowSelectionModel.
Set your selection model to single select by configuring the sm (selection model) in grid panel as show below:
sm: new Ext.grid.RowSelectionModel({singleSelect:true})
Update:
Try reloading the grid using the load method or loadData method of the grid's store. Are you updating the grid on the client side? then maybe you can use loadData method. If you are using to get data from remote.. you can use load method. I use load method to update my grid with new records (after some user actions like add,refresh etc). Or you could simply reload as follows:
grid.getStore().reload();

Resources