Not able to pass parameter to function - javascript

I am trying to pass the value in the state as a parameter to the Function.addAddOnData to which calls the setaddOndatatypes function with " addOnCategory" as a parameter, the parameter is not getting passed on doing console.log it shows blank as the response.
First function call:
const onSubmit = e => {
e.preventDefault();
fileUpload(fileInputRef);
if (!state.loading) {
addAddOnDataToDb(
state.addOnCategory,
state.itemName,
state.itemPrice,
state.itemIconURL
);
}
};
Function:
const addAddOnDataToDb = (
itemName,
itemIconURL,
itemPrice,
addOnCategory
) => {
console.log(addOnCategory);
const addOnType = setAddOnItemType(addOnCategory);
console.log(addOnType);
const addOnBody = JSON.stringify({
itemName,
itemIconURL,
itemPrice,
addOnType
});
console.log(addOnBody);
const config = {
headers: {
'Content-Type': 'application/JSON'
}
};
axios.post('/api/v1/addOn', addOnBody, config);
};
Call to setAddOnItemType
const setAddOnItemType = addOnCategory => {
console.log(addOnCategory);
switch (addOnCategory) {
case 'Add on':
return 'addOn';
case 'Flavours':
return 'flavour';
}
};

You have wrong ordering of arguments at the addAddOnDataToDb call side.
you defined the function like:
const addAddOnDataToDb = (
itemName,
itemIconURL,
itemPrice,
addOnCategory
) => {
....
}
And your call looks like:
addAddOnDataToDb(
state.addOnCategory,
state.itemName,
state.itemPrice,
state.itemIconURL
);
state.addOnCategory should be passed as the last argument to the function call. Also the price and icon url are also in wrong order.
addAddOnDataToDb(
state.itemName,
state.itemIconURL,
state.itemPrice,
state.addOnCategory,
);

Related

how to append data in each call react redux

I would like to know how to handle multiple call to action with different parameters.
How to append the data received for each parameter call in react redux.
Is there any other way to do, or for each id should have seperate action
action.js
export const saleSumm= payload =>
queryApi({
request: CONSTANTS.SALES_SUMMARY,
url: `/api/detail`,
encode: false,
success: CONSTANTS.SUMMARY_SUCCESS,
failure: CONSTANTS.SUMMARY_FAILURE,
...payload
});
//reducer.js
case CONSTANTS.SUMMARY_SUCCESS:
case CONSTANTS.SUMMARY_FAILURE:
return {
...state,
SaleSumm: data, //should append data for each id
apiPending: false,
errormsg: errormsg,
servererror: servererror || ""
};
//index.js
fetchData = (id) =>{
const body = {
id: id,
cn: "MY"
}
return body;
}
renderData=(item)=>{
var mode = ["1010", "1111"];
mode.map(i=>
this.props.dispatch(saleSumm(this.fetchData(i))))
}
render(){
return(
<div>{this.renderData(this.props)}</div>
)
}

unable to select all checkboxes in tree using angular2-tree on init

Objective : i have a button named "feed data" so when ever i click it the data will be loaded i mean the tree with checkboxes here my requirement is when ever i click it along with data all the check boxes have to be checked on init i tried using
this.treeComp.treeModel.doForAll((node: TreeNode) => node.setIsSelected(true));
but it is not working below is my code
click(tree: TreeModel) {
this.arrayData = [];
let result: any = {};
let rs = [];
console.log(tree.selectedLeafNodeIds);
Object.keys(tree.selectedLeafNodeIds).forEach(x => {
let node: TreeNode = tree.getNodeById(x);
// console.log(node);
if (node.isSelected) {
if (node.parent.data.name) //if the node has parent
{
rs.push(node.parent.data.name + '.' + node.data.name);
if (!result[node.parent.data.name]) //If the parent is not in the object
result[node.parent.data.name] = {} //create
result[node.parent.data.name][node.data.name] = true;
}
else {
if (!result[node.data.name]) //If the node is not in the object
result[node.data.name] = {} //create
rs.push(node.data.name);
}
}
})
this.arrayData = rs;
tree.selectedLeafNodeIds = {};
}
selectAllNodes() {
this.treeComp.treeModel.doForAll((node: TreeNode) => node.setIsSelected(true));
// firstNode.setIsSelected(true);
}
onTreeLoad(){
console.log('tree');
}
feedData() {
const results = Object.keys(this.data.info).map(k => ({
name: k,
children: this.data.info[k].properties
? Object.keys(this.data.info[k].properties).map(kk => ({ name: kk }))
: []
}));
this.nodes = results;
}
feedAnother() {
const results = Object.keys(this.dataa.info).map(k => ({
name: k,
children: this.dataa.info[k].properties
? Object.keys(this.dataa.info[k].properties).map(kk => ({ name: kk }))
: []
}));
this.nodes = results;
}
onActivate(event) {
this.selectedDataList.push(event.node.data);
console.log(this.selectedDataList)
}
onDeactivate(event) {
const index = this.selectedDataList.indexOf(event.node.data);
this.selectedDataList.splice(index, 1);
console.log(this.selectedDataList)
}
below is my stackblitz https://stackblitz.com/edit/angular-hrbppy
Use updatedata and initialized event to update the tree view to check all checkboxes.
app.component.html
<tree-root #tree *ngIf ="nodes" [nodes]="nodes" [options]="options" [focused]="true"
(initialized)="onTreeLoad()"
(updateData)="updateData()"
(select)="onActivate($event)"
(deselect)="onDeactivate($event)">
</tree-root>
It'll initiate tree-root component only if nodes variable is available,
then in the initialized and updateData event call selectAllNodes method to select all checkboxes.
app.component.ts
updateData() {
this.selectAllNodes();
}
onTreeLoad(){
this.selectAllNodes();
}
Refer to this slackblitz for working example.
just, in your function feed data call to your function this.selectAllNodes() enclosed in a setTimeout. You can see your forked stackblitz
setTimeout(()=>{
this.selectAllNodes()
})
NOTE: I see in your code you try to control in diferents ways the items selected. I simplified using a recursive function.
In this.treeComp.treeModel.selectedLeafNodeIds we have the items that are changed, so
getAllChecked()
{
const itemsChecked=this.getData(
this.treeComp.treeModel.selectedLeafNodeIds,null)
console.log(itemsChecked);
}
getData(nodesChanged,nodes) {
nodes=nodes||this.treeComp.treeModel.nodes
let data: any[] = []
nodes.forEach((node: any) => {
//in nodesChanged we has object like {1200002:true,123132321:false...}
if (nodesChanged[node.id]) //can be not changed, and then it's null because
//it's not in object or can be changed to false
data.push({id:node.id,name:node.name})
//or data.push(node.name); //if only need the "name"
if (node.children)
data=[...data,...this.getData(nodesChanged,node.children)]
}
);
return data
}
Updated I updated the function getData to include the "parent" of the node, but looking the code of #Raghul selvam, his function like me more than mine.
getData(nodesChanged,nodes,prefix) {
nodes=nodes||this.treeComp.treeModel.nodes
let data: any[] = []
nodes.forEach((node: any) => {
if (nodesChanged[node.id])
data.push(prefix?prefix+"."+node.name:node.name)
if (node.children)
data=[...data,...this.getData(nodesChanged,node.children,prefix?prefix+"."+node.name:node.name)]
}
);
return data
}
And call it as
this.getData(this.treeComp.treeModel.selectedLeafNodeIds,null,"")
You could add this in your onTreeLoad function. You could add a boolean flag(treeLoaded) for tracking if the tree has loaded or not.
onTreeLoad(tree){
this.selectAllNodes();
this.treeLoaded = true;
}

this `implicitly` has type any it does not have type annotation?

i am calling function this.buildSingleRequestBody it is throwing error this implicilty has type any it does not have type annotation , not sure what has implemented wrong.
main.ts
private buildRequestArray(specialtyMembers: ISpecialtyInfoObj[],
request: ICombinedAccountBalanceRequest): IRequestURL[] {
const specialtyUrl = urlConfig.specialtyBaseUrl + "payments/getAccountBalance";
const serviceContext = request.header.serviceContext;
const requestArray: IRequestURL[] = specialtyMembers.map(function(member) {
const body: any = this.buildSingleRequestBody(member, serviceContext);
return {url: specialtyUrl, body};
});
return requestArray;
}
private buildSingleRequestBody(specialtyMember: ISpecialtyInfoObj, serviceContext: IServiceContext) {
return {
"header": {
serviceContext
},
"specialtyId": specialtyMember.Id || "78988716",
"specialtySource": specialtyMember.specialtySource || "HBS"
};
}
function does not capture this from the declaration context, rather this is decided by the caller. Since you use function when you call map, the this inside anonymous function will not refer to the class. Since map does not explicitly declare what this it will pass into the function, the type of this will implicitly be any inside the anonymous function, hence the error.
Use an arrow function instead as that will capture the declaration this
private buildRequestArray(specialtyMembers: ISpecialtyInfoObj[],
request: ICombinedAccountBalanceRequest): IRequestURL[] {
const specialtyUrl = urlConfig.specialtyBaseUrl + "payments/getAccountBalance";
const serviceContext = request.header.serviceContext;
const requestArray: IRequestURL[] = specialtyMembers.map((member) => {
const body: any = this.buildSingleRequestBody(member, serviceContext);
return {url: specialtyUrl, body};
});
return requestArray;
}
private buildSingleRequestBody(specialtyMember: ISpecialtyInfoObj, serviceContext: IServiceContext) {
return {
"header": {
serviceContext
},
"specialtyId": specialtyMember.Id || "78988716",
"specialtySource": specialtyMember.specialtySource || "HBS"
};
}

eval or alternative to call an object through a variable inside then() inside a function

I import 'Bank' in a function, and i want to use inside in then().
I'm using eval(table) but i get th error: ReferenceError: Bank is not defined',
import { Bank } from './ormconnectors';
const genericResolver = ( table, action , values ) => {
if (action==='list') {
const errors = [];
return Auth.isAuthenticated()
.then(() => {
return eval(table).findAll()
}
}
}
calling this function:
genericResolver ( 'Bank', ..... );
Why are you using eval at all?
You should instead switch to accessing properties by name:
import { Bank } from './ormconnectors';
const tableByName = {"Bank": Bank};
...
return tableByName[table].findAll()

How to pass data from one function to another function that is an argument of the first function

In the below example, when using getData();, is it possible to access the data contained in its object map within a new function – ie. useData(); – that is an argument of getData();?
const getData = (useData) => {
const myData = {
0: { title: 'Hello' },
1: { title: 'World!' }
};
Object.keys(myData).map((item) => {
useData();
});
}
getData(console.log(
/**
* Somehow access data represented by `myData` and `item`
* in above object map along the lines of `myData[item].title`
*/
));
Do you want to achieve something like that?
You can call useData with some arguments inside map function. You can't call some function like console.log as argument to getData function in this case.
const getData = useData => {
const myData = {
0: { title: "Hello" },
1: { title: "World!" },
};
Object.keys(myData).map(item => {
useData(myData[item]);
});
};
getData(console.log);
Yes, that is the default behaviour. But you need to pass a function(console.log) instead of a function invocation(console.log()) and invoke it only later.
const getData = (useData) => {
const myData = {
0: { title: 'Hello' },
1: { title: 'World!' }
};
Object.keys(myData).map((item) => {
useData.apply(console, [item]);
useData.apply(console, [ myData[item].title ]);
//or useData(myData[item].title)
});
}
getData(console.log);
getData(console.log('something'));
is same as:
let x = console.log('something');
getData(x);

Categories