VS Code Formatting JSX with new lines in useCallback() - visual-studio-code

VSC's jsx formatting looks weird.
If there's no param in useCallback it looks fine, but there's new line when there's param. And also there's new line in dependency array when useCallback method has params.
I want to change this as in the case where there are no parameters.
Any Ideas?
const onSubmitEditing = useCallback(
({nativeEvent}) => {
setSearchQuery(nativeEvent.text);
},
[setSearchQuery],
);
const clearText = useCallback(() => {
setSearchBoxText('');
}, [setSearchBoxText]);
This is my .prettierrc.js.
And I use 'Prettier - Code formatter' as default formatter.
module.exports = {
bracketSpacing: false,
jsxBracketSameLine: true,
singleQuote: true,
trailingComma: 'all',
};

Related

Redux toolkit slice. Pure functions inside field reducers

Sup ya. Just wanna specify can we use it? I think we can just wanna be sure 100%
https://codesandbox.io/s/redux-toolkit-state-new-array-4sswi?file=/src/redux/slices/slice.js:111-425
const someSlice = createSlice({
name: "someSlice",
initialState: {
users: [],
status: ""
},
reducers: {
actionSuccess: (state, { payload }) => {
state.users = payload.users;
},
actionFailure: (state) => {
// can we use here function?
statusHandler(state)
}
}
});
A reducer should not trigger any side effects. That is, it should not do anything other than change the contents of the state. So you should not call a statusHandler which would trigger external effects.
If your statusHandler function does nothing but update the state, that does seem to work in my testing and I'm not aware of any reason why it shouldn't be okay.
Redux Toolkit uses Immer behind the scenes to deal with immutable updates, so this question basically boils down to whether these two functions, updatedInline and updatedExternally, are equivalent. They are, as far as I can tell.
const {produce} = immer;
const initialState = {
status: ''
};
const updatedInline = produce( initialState, draft => {
draft.status = 'failed';
})
const mutateStatus = (state) => {
state.status = 'failed';
}
const updatedExternally = produce( initialState, mutateStatus )
console.log("Updated Inline: \n", updatedInline);
console.log("Updated Externally: \n", updatedExternally);
<script src="https://cdn.jsdelivr.net/npm/immer#8.0.1/dist/immer.umd.production.min.js"></script>

ReactDataGrid row selection does not work

I am trying to build data table using react and react-data-grid version "^7.0.0-canary.16",
The render method looks like this:
render() {
return (
<div className={"component"}>
<ReactDataGrid width={600} height={400}
rowKey="id"
columns={this.state.columns}
rows={this.state.rows}
onRowClick={this.onRowClick}
rowSelection={{
showCheckbox: true,
enableShiftSelect: true,
onRowsSelected: this.onRowsSelected,
onRowsDeselected: this.onRowsDeselected,
selectBy: {
indexes: this.state.selectedIndexes
}
}}
/>
</div>
)
}
So following the documentation on page https://adazzle.github.io/react-data-grid/docs/examples/row-selection
it should display checkbox in first column and when I select the checkbox it should call method this.onRowsSelected.
Alas, no checkbox is shown and no matter how I click the this.onRowsSelected method is never called.
On the other hand the method this.onRowClick is called, whenever I click somewhere in the table.
Does anyone have experience with this?
It seems to be showing the checkboxes with "react-data-grid": "6.1.0"
Although, I'm having issue with the checkboxes when we filter the data. The rowIdx changes and we lose context of that was previously selected. We want to make BE calls on selected Data. I tried changing it to use the row.id but no luck. It messes up the selection.
Here is a hook for managing the selection
import {useState} from 'react';
export const useRowSelection = () => {
const [selectedIndexes, setSelectedIndexes] = useState([]);
const onRowsSelected = rows => {
setSelectedIndexes(prevState => {
return prevState.concat(rows.map(r => r.rowIdx));
});
};
const onRowsDeselected = rows => {
let rowIndexes = rows.map(r => r.rowIdx);
setSelectedIndexes(prevState => {
return prevState.filter(i => rowIndexes.indexOf(i) === -1);
});
};
return {
selectedIndexes,
onRowsDeselected,
onRowsSelected,
};
};
Pass them to the RDG
const {selectedIndexes, onRowsDeselected, onRowsSelected} = useRowSelection();
const rowSelectionProps = enableRowSelection
? {
showCheckbox: true,
enableShiftSelect: true,
onRowsSelected: onRowsSelected,
onRowsDeselected: onRowsDeselected,
selectBy: {
indexes: selectedIndexes,
},
}
: undefined;
<ReactDataGrid
columns={columnDefinition}
getValidFilterValues={getFilterValues}
rowGetter={i => filteredData[i]}
rowsCount={filteredData.length}
onAddFilter={filter => handleOnAddFilter(filter)}
onClearFilters={() => handleOnCleanFilters()}
toolbar={toolbar}
contextMenu={contextMenu}
RowsContainer={ContextMenuTrigger}
rowSelection={rowSelectionProps}
rowKey="id"
/>

Coffeescript compile error

i just installed Coffeescript and tried a test compile but it always drop me errors for silly things, Coffeescript only compile correctly when only Coffeescript syntax is used?
because if yes then i understand the error.
concDev.js contents:
/*! ProjectName 2013-08-18 06:08:39 */
$(function() {
// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
});
// New file
$(function() {
// Handler for .ready() called.
});
You can't use C style comments in Coffeescript.
This
/*! Project Name ...*/
should be this
# Project Name ...
More generally, if you're using the Coffeescript compiler, you need valid coffeescript syntax and can't mix and match JS and coffeescript files.
Update
You're trying to pass a JS file to a coffeescript compiler. The coffee compiler accepts a coffeescript file, and compiles it to a JS file. Your file in Coffeescript would look something like this:
#! ProjectName 2013-08-18 06:08:39 */
$ ->
# Avoid `console` errors in browsers that lack a console.
do ->
noop = -> null
methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
]
length = methods.length
console = window.console = window.console || {}
while length--
method = methods[length]
# Only stub undefined methods.
if !console[method]
console[method] = noop;
// New file
$ ->
#Handler for .ready() called.
If you really need to have some JS in your coffeescript file, you can embed it using backticks like this
a = `(function() x{ return 2;})()`

Extjs - autocomplete filter 2 properties

By following this example http://dev.sencha.com/deploy/ext-4.1.0-gpl/examples/form/forum-search.html
I could apply the auto-complete feature on my combo box, using php/postgresql query retrieves the names then:
{
xtype: 'combo',
store: ds,
hideTrigger:true,
typeAhead: false,
id: 'search_input_text',
width: 187,
queryMode: 'remote',
hideLabel: true,
queryParam: 'query',
displayField: 'first_name',
valueField: 'first_name',
listConfig: {
loadingText: 'Loading...',
getInnerTpl: function() {
return '{first_name}';
}}
listeners: {
buffer: 50,
change: function() {
var store = this.store;
store.clearFilter();
store.filter({
property: 'first_name',
anyMatch: true,
value : this.getValue()
});
}
}
}
Now, I need to edit this to let user enter either the first or last name of the student, and then each name entered (first or last) will be shown in the combo box.
So, I edited the query to make it retrieve the names :
SELECT first_name, last_name FROM students WHERE first_name ILIKE '%$query%' OR last_name ILIKE '%$query%' ";
and:
displayField: 'first_name'+'last_name',
valueField: 'first_name'+'last_name',
return '{first_name}'+'{last_name}';
store.filter({
property: 'first_name',
anyMatch: true,
value : this.getValue()
},
{
property: 'last_name',
anyMatch: true,
value : this.getValue()
}
but still, it retrieves only first names according to what user types,
Note that if I use this alone:
store.filter({
property: 'last_name',
anyMatch: true,
value : this.getValue()
});
it works fine with last names only.
You can apply multiple filters to data store like this:
var filters = [
new Ext.util.Filter({
filterFn: function(item){return item.get('first_name') == this.getValue() || item.get('last_name') == this.getValue();
}
})
];
store.filter(filters);
The above code block is just an idea on how to apply multiple filters in the same field. Notice the double-pipe "||". You can use "&&" as per your needs. It is like SQL query.

cakePHP + extjs row editor and REST

I've implemented REST routing in cakePHP to properly route REST style requests to the proper methods in my controller.
This is what I've added to my routes.php
Router::mapResources(array('object_fields'));
This properly routes the REST requests to my index/add/edit/delete methods inside my controller.
In my EXTJS grid I am using the row editor with a restful store to achieve CRUD behavior.
Here is the code for my grid
myapp.object_field_grid = Ext.extend(Ext.grid.GridPanel, {
closable: true,
stripeRows: true,
frame: true,
viewConfig: {
forceFit: true
},
editor: new Ext.ux.grid.RowEditor({
saveText: 'Update',
}),
onAdd : function(btn, ev){
var u = new this.store.recordType({
name : '',
type: '',
});
this.editor.stopEditing();
this.store.insert(0, u);
this.editor.startEditing(0);
},
onDelete : function(){
},
initComponent: function() {
var proxy = new Ext.data.HttpProxy({
url: 'object_fields/',
});
var reader = new Ext.data.JsonReader({
totalProperty: 'totalCount',
successProperty: 'success',
idProperty: 'id',
root: 'data',
messageProperty: 'message'
}, [
{name: 'id'},
{name: 'name', allowBlank: false},
{name: 'type', allowBlank: false},
]);
var writer = new Ext.data.JsonWriter({
encode: false,
});
var store = new Ext.data.Store({
baseParams: {id: this.object_id},
id: 'object_fields',
restful: true,
proxy: proxy,
reader: reader,
writer: writer,
});
store.load();
var object_field_columns = [
// {header: "id", width: 250, sortable: true, dataIndex: 'id', editor: new Ext.form.TextField({})},
{header: "name", width: 250, sortable: true, dataIndex: 'name', editor: new Ext.form.TextField({})},
{header: "type", width: 250, sortable: true, dataIndex: 'type', editor: new Ext.form.ComboBox({editable: false, store:['STRING', 'NUMBER']})},
];
var config = {
columns: object_field_columns,
store: store,
plugins: [this.editor],
//autoHeight: true,
height: 200,
tbar: [{
text: 'Add',
iconCls: 'silk-add',
handler: this.onAdd,
scope: this,
}, '-', {
text: 'Delete',
iconCls: 'silk-delete',
handler: this.onDelete,
scope: this,
}, '-'],
}
Ext.apply(this, Ext.apply(this.initialConfig, config));
myapp.object_field_grid.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
this.store.load();
myapp.object_field_grid.superclass.onRender.apply(this, arguments);
}
});
Ext.reg('object_field_grid', myapp.object_field_grid); // register xtype
My GET/POST requests are being properly routed to my index/add methods inside my controller and I am able to easily retrieve the paramaters that I pass it in the request.
My problem is with the update functionality PUT request. The PUT request does get successfully routed to my edit method inside the controller.
This is what the request looks like in firebug
http://server.local/object_fields/20
JSON
data
Object { name="test7777777777", more...}
id
"18"
Source
{"id":"18","data":{"name":"test7777777777","id":"20"}}
Inside my edit method I'm not receiving my array that I passed through the PUT request.
When I dump $this->params inside my edit method this is what is in the array.
([id] => 20
[named] => Array
(
)
[pass] => Array
(
[0] => 20
)
[controller] => object_fields
[action] => edit
[[method]] => PUT
[plugin] =>
[url] => Array
(
[ext] => html
[url] => object_fields/20
)
[form] => Array
(
)
[isAjax] => 1
)
How can I properly receive my array through the PUT request inside my edit method?
UPDATE:
I am able to retrieve my array using the following code inside the edit method
function edit($id){
$this->autoRender = false;
echo 'edit';
$raw = '';
$httpContent = fopen('php://input', 'r');
while ($kb = fread($httpContent, 1024)) {
$raw .= $kb;
}
fclose($httpContent);
$params = array();
parse_str($raw, $params);
print_r($params);
}
The question is now why does cakePHP not do this automaticly?
put this in your app_controller.php:
public function beforeFilter() {
if (
isset($this->RequestHandler) &&
$this->RequestHandler->requestedWith('json') &&
(
$this->RequestHandler->isPost() ||
$this->RequestHandler->isPut()
)
) {
$jsonData = json_decode(utf8_encode(trim(file_get_contents('php://input'))), true);
if (is_array($jsonData)) {
$this->data = $jsonData;
unset($jsonData);
}
}
}