import { OrderSummary } from "#/services/order/data";
Below is my state declaration
let [orderSummary, setOrderSummary] = useState<OrderSummaryResponse>({
Id: 0,
TableId: 0,
TableName: '',
MerchantId: 0,
StoreId: 0,
StoreName: '',
BrandName: '',
IsUnifyQR: false,
Discount: 0,
ServiceCharge: 0,
GST: 0,
RoundingAdjustment: 0,
TotalAmount: 0,
SubTotalAmount: 0,
ServiceChargeAmount: 0,
GSTAmount: 0,
CreatedAt: '',
Items: [
{
MerchantId: 0,
StoreId: 0,
StoreName: '',
ItemId: 0,
ProductId: 0,
ProductName: '',
TotalAmount: 0,
Quantity: 0,
Note: '',
Choices: [
{
OptionSelectedName: '',
ProductOptionId: 0,
OptionSelected: null,
MultiOptionsSelected: null,
OneChoiceWithValueSelected: {
OptionSelected: 0,
Quantity: 0,
Price: 0,
},
MultioptionWithValueSelected: [],
},
],
},
],
Categories: [''],
});
if I have a few usestate like above, my code looks very lengthy how to simplify that.
getting error if I use like this
let [orderSummary, setOrderSummary] = useState<OrderSummary>({})
let [orderSummary, setOrderSummary] = useState<OrderSummary>({} as any)
You can use type like this:
let [orderSummary, setOrderSummary] = useState<OrderSummary | null>(null)
And when you want to use orderSummary. You can add optional chaining like this:
orderSummary?.StoreId
Related
I am new to the react redux . Here, what I am doing is ,
const initialState = {
Low: [
{
id: 0,
technologyId: 0,
technology: '',
level: 'EASY'
}
],
Medium: [
{
id: 0,
technologyId: 0,
technology: '',
level: 'MEDIUM'
}
],
High: [
{
id: 0,
technologyId: 0,
technology: '',
level: 'TOUGH'
}
]
}
Now,In my reducer ,
export default function QuizData(state = initialState, action) {
switch (action.type) {
case QUIZ_DATA:
return {
...state,
Low: action.data,
error: false,
}
case RESET_QUIZ_CRITERIA: {
console.log("intial state is ", ...state);
return {
...state
}
Now, here what happens is after some manipulations, this objects gets changes with every key is having some values. like,
So, This gets changed.
{
Low: [
{
id: 0,
technologyId: 11,
technology: 'xsxs',
level: 'EASY'
}
],
Medium: [
{
id: 0,
technologyId: 22,
technology: 'swwsw',
level: 'MEDIUM'
}
],
High: [
{
id: 0,
technologyId: 110,
technology: 'xsxsx',
level: 'TOUGH'
}
]
}
for resetting my action is like ,
export function resetPreviousQuizSelectionCriteria() {
console.log("Calling this");
return {
type: RESET_QUIZ_CRITERIA
}
}
Now, what I want to do is that ,
When user clicks a button that time I want to change this to the initial state.
So that it will not have any values as it should be same as by default.
So, Can any one one suggest me the solution?
I think returning initial State should resolve the issue.
case RESET_QUIZ_CRITERIA: {
console.log("intial state is ", ...state);
return {
...initialState
}
try this if it works.
I need to update the value of an element in the second array and change it to completed count of first array...
I need to do it using JSON files, and the completed count of first array need to be the value assigned that is 30 sorry for not being clear before..
I've tried using the parseInt().. i'm new to javascript itself...
function printjson() {
var first = new Array(
{
projectId: '230',
title: 'Nikhil',
status: 'Nikhil',
seenCount: 0,
inProgressCount: 0,
completedCount: 30
},
{
projectId: null,
title: null,
status: null,
seenCount: 0,
inProgressCount: 0,
completedCount: 1,
}
);
var second = new Array(
{
id: '230',
name: 'project-qa-test',
customQuestion: 'What did you get done today?',
maxSyncItems: null,
orderIndex: 0,
hidden: false,
dones: [],
unReported: 0,
seenCount: 0,
inProgressCount: 0,
completedCount: 0,
}
);
if (first.projectId == second.Id) {
second.completedCount = 230;
}
console.log(second);
console.log(second.completedCount);
}
printjson();
expected result should be:
[
{
id: '230',
name: 'project-qa-test',
customQuestion: 'What did you get done today?',
maxSyncItems: null,
orderIndex: 0,
hidden: false,
dones: [],
unReported: 0,
seenCount: 0,
inProgressCount: 0,
completedCount: 230
},
]
230
but I'm getting:
[
{
id: '230',
name: 'project-qa-test',
customQuestion: 'What did you get done today?',
maxSyncItems: null,
orderIndex: 0,
hidden: false,
dones: [],
unReported: 0,
seenCount: 0,
inProgressCount: 0,
completedCount: 0
},
completedCount: 230
]
230
Since first and second are arrays, you have to use proper indexes to get/set the object properties.
Try:
if (first[0].projectId == second[0].id){
second[0].completedCount = 230;
}
function printjson()
{
var first=new Array(
{
projectId: '230',
title: 'Nikhil',
status: 'Nikhil',
seenCount: 0,
inProgressCount: 0,
completedCount: 30
},
{
projectId: null,
title: null,
status: null,
seenCount: 0,
inProgressCount: 0,
completedCount: 1 ,
}
);
var second=new Array(
{
id: '230',
name: 'project-qa-test',
customQuestion: 'What did you get done today?',
maxSyncItems: null,
orderIndex: 0,
hidden: false,
dones: [],
unReported: 0,
seenCount: 0,
inProgressCount: 0,
completedCount: 0,
}
);
if (first[0].projectId == second[0].id){
second[0].completedCount = 230;
}
console.log(second);
console.log(second[0].completedCount);
}
printjson();
I am new to the react-redux.
Here I have an object which is like,
const initialState = {
Low: [
{
id: 0,
technologyId: 0,
technology: '',
type: '',
count: '',
allowded: 6,
level: 'EASY'
}
],
Medium: [
{
id: 0,
technologyId: 0,
technology: '',
type: '',
count: '',
allowded: 7,
level: 'MEDIUM'
}
],
High: [
{
id: 0,
technologyId: 0,
technology: '',
type: '',
count: '',
allowded: 7,
level: 'TOUGH'
}
]
}
Now, this value is set it in the reducer I am taking it as a props.
Now, onchnage here the object property gets change from one of these obj.
So, Here the way I am updating it is ,
onChange(event, tobeupdated, id, type, noc, data) {
let newData = { ...this.props.data };
if (newData) {
let data = newData[type].map((object, index) => {
if (object.id === id) {
object[tobeupdated] = event.target.value;
});
}
}
So,Here will I be updating the existing object ?
Or is there any another way ?
What I tried was,
{...object, [tobeupdated]: event.target.value}
it is giving the compile time errors .
How can I resolve this ?
I have this code into my app that returns some job feed in json format:
My code looks as below:
JobFeed.find().sort('-created').exec(function (err, feeds) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
_.forEach(feeds, function (row, key) {
console.log(row.data.title); // showing undefined
});
res.jsonp(feeds);
}
});
and the json looks like below:
{ data:
{ isSaved: null,
client:
{ lastContractTitle: null,
feedbackText: '4.78 Stars, based on 13 feedbacks',
paymentVerificationStatus: 1,
lastContractPlatform: null,
totalFeedback: 4.7819242373,
location: [Object],
lastContractRid: 0,
edcUserId: 3728985,
totalReviews: 13,
companyRid: 0,
spentTier: '$7,500+',
companyName: null },
amount: { amount: 0, currencyCode: 'USD' },
createdOn: '2016-10-13T06:30:54+00:00',
skills: [ [Object], [Object], [Object], [Object] ],
enterpriseJob: false,
ciphertext: '~01026b31d972ed826b',
proposalsTier: null,
description: 'Hello! We\'re currently searching for a developer with',
category2: 'Web, Mobile & Software Dev',
type: 2,
tierText: 'Intermediate ($$)',
relevance:
{ hoursInactive: 0,
id: 208660674,
publishTime: '1476340265000',
recommendedEffectiveCandidates: 2,
effectiveCandidates: 3,
uniqueImpressions: 0 },
isApplied: null,
engagement: '30+ hrs/week',
recno: 208660674,
title: 'Server-side and Client-side Game Developer for Indie MMO',
freelancersToHire: 0,
maxAmount: { amount: 0, currencyCode: 'USD' },
duration: 'More than 6 months',
subcategory2: 'Game Development',
sticky: false,
stickyLabel: '',
feedback: null },
id: 57ffcdbf717ca50cf0b4cbc1 }
{ data:
{ isSaved: null,
client:
{ lastContractTitle: null,
feedbackText: 'No feedback yet',
paymentVerificationStatus: 1,
lastContractPlatform: null,
totalFeedback: 0,
location: [Object],
lastContractRid: 0,
edcUserId: 0,
totalReviews: 0,
companyRid: 0,
spentTier: '$100+',
companyName: null },
amount: { amount: 0, currencyCode: 'USD' },
createdOn: '2016-10-13T06:30:51+00:00',
skills: [ [Object], [Object], [Object] ],
enterpriseJob: false,
ciphertext: '~01c59efb9135ed91d0',
proposalsTier: null,
description: 'Hello! We\'re currently searching for a developer with',
category2: 'Web, Mobile & Software Dev',
type: 2,
tierText: 'Entry Level ($)',
relevance:
{ hoursInactive: 0,
id: 208660673,
publishTime: '1476340266000',
recommendedEffectiveCandidates: 18,
effectiveCandidates: 74,
uniqueImpressions: 0 },
isApplied: null,
engagement: 'Less than 10 hrs/week',
recno: 208660673,
title: 'Wordpress & Stripe developer',
freelancersToHire: 0,
maxAmount: { amount: 0, currencyCode: 'USD' },
duration: 'More than 6 months',
subcategory2: 'Web Development',
sticky: false,
stickyLabel: '',
feedback: null },
id: 57ffcdbf717ca50cf0b4cbc2 }
{ data:
{ isSaved: null,
client:
{ lastContractTitle: null,
feedbackText: 'No feedback yet',
paymentVerificationStatus: 5,
lastContractPlatform: null,
totalFeedback: 0,
location: [Object],
lastContractRid: 0,
edcUserId: 0,
totalReviews: 0,
companyRid: 0,
spentTier: 'Less than $100',
companyName: null },
amount: { amount: 2000, currencyCode: 'USD' },
createdOn: '2016-10-13T06:30:18+00:00',
skills: [ [Object], [Object] ],
enterpriseJob: false,
ciphertext: '~0101449f91585e8e16',
proposalsTier: null,
description: 'I need a Christmas card app before 15th Dec.n',
category2: 'Web, Mobile & Software Dev',
type: 1,
tierText: 'Intermediate ($$)',
relevance:
{ hoursInactive: 0,
id: 208660669,
publishTime: '1476340233000',
recommendedEffectiveCandidates: 7,
effectiveCandidates: 52,
uniqueImpressions: 0 },
isApplied: null,
engagement: null,
recno: 208660669,
title: 'Christmas Card iPhone App',
freelancersToHire: 0,
maxAmount: { amount: 0, currencyCode: 'USD' },
duration: null,
subcategory2: 'Mobile Development',
sticky: false,
stickyLabel: '',
feedback: null },
id: 57ffcdbf717ca50cf0b4cbc3 }
{ data:
{ isSaved: null,
client:
{ lastContractTitle: null,
feedbackText: '4.88 Stars, based on 102 feedbacks',
paymentVerificationStatus: 1,
lastContractPlatform: null,
totalFeedback: 4.8843944128,
location: [Object],
lastContractRid: 0,
edcUserId: 0,
totalReviews: 102,
companyRid: 0,
spentTier: '$25,000+',
companyName: null },
amount: { amount: 100, currencyCode: 'USD' },
createdOn: '2016-10-13T06:30:00+00:00',
skills:
[ [Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object] ],
enterpriseJob: false,
ciphertext: '~01a04eab3b05372652',
proposalsTier: null,
description: 'Hello! We\'re currently searching for a developer with',
category2: 'Writing',
type: 1,
tierText: 'Entry Level ($)',
relevance:
{ hoursInactive: 0,
id: 208660668,
publishTime: '1476340202000',
recommendedEffectiveCandidates: 2,
effectiveCandidates: 6,
uniqueImpressions: 0 },
isApplied: null,
engagement: null,
recno: 208660668,
title: 'Filipino Blog/Content Writers For a Filipino Site (Using WordPress)',
freelancersToHire: 3,
maxAmount: { amount: 0, currencyCode: 'USD' },
duration: null,
subcategory2: 'Article & Blog Writing',
sticky: false,
stickyLabel: '',
feedback: null },
id: 57ffcdbf717ca50cf0b4cbc4 }
The foreach that I have, seems to iterate through each of items, but there is no way I can get the title for each item. Any Help?
I'm not really sure what you're trying to do, but something like this should work if the data is indeed what you have on your comments:
feeds.forEach(function(feed){
console.log(feed.data.title);
});
If you want faster performance, use the regular for loop. I tested this out on my project. Let me know if this doesn't work.
I can't even figure out how this is possible
when I do this:
console.error(order.Items[i]);
I get this:
{ ItemURL: '',
IsBundle: false,
GiftTaxPrice: '0',
GiftPrice: '0',
GiftNotes: null,
GiftMessage: null,
RecyclingFee: 0,
ShippingTaxPrice: 0,
ShippingPrice: 6,
TaxPrice: 0,
UnitPrice: 3,
Quantity: 1,
Title: 'HICKIES TEST PRODUCT',
Sku: 'PLSB_TEST_PRODUCT',
SiteListingID: '30000418',
SiteOrderItemID: '',
ProductID: 72176,
OrderID: 100152,
ProfileID: 12021605,
ID: 156,
CustomFields: [],
Adjustments: [],
FulfillmentItems: [],
Promotions: [] }
But for some reason when I try to access Sku with
console.error(order.Items[i].Sku);
I get:
undefined
Yet magically for some reason
console.error(order.Items[i].Quantity);
or
console.error(order.Items[i].UnitPrice);
Print:
1
and
3
Respectively
---EDIT
As requested
for (var i = 0; i < order.Items.length; i++) {
formatedOrder['Subtotal'] += parseInt(order.Items[i].Quantity) * parseFloat(order.Items[i].UnitPrice);
console.error(order.Items[i]);
console.error(order.Items[i].Sku);
console.error(order.Items[i]['Sku']);
formatedOrder["OrderLines"].push({
"Product": order.Items[i].Sku,
"Quantity": parseInt(order.Items[i].Quantity),
"Price": parseFloat(order.Items[i].UnitPrice)
});
}
As Requested the Items Array :
[{ ItemURL: '',
IsBundle: false,
GiftTaxPrice: '0',
GiftPrice: '0',
GiftNotes: null,
GiftMessage: null,
RecyclingFee: 0,
ShippingTaxPrice: 0,
ShippingPrice: 6,
TaxPrice: 0,
UnitPrice: 3,
Quantity: 1,
Title: 'HICKIES TEST PRODUCT',
Sku: 'PLSB_TEST_PRODUCT',
SiteListingID: '30000418',
SiteOrderItemID: '',
ProductID: 72176,
OrderID: 100152,
ProfileID: 12021605,
ID: 156,
CustomFields: [],
Adjustments: [],
FulfillmentItems: [],
Promotions: [] }]
Try this, I have no reason to use console.error() use console.log() instead
for (var i = 0; i < order.Items.length; i++) {
formatedOrder['Subtotal'] += parseInt(order.Items[i].Quantity) * parseFloat(order.Items[i].UnitPrice);
console.log(order.Items[i]);
console.log(order.Items[i].Sku);
console.log(order.Items[i]['Sku']);
formatedOrder["OrderLines"].push({
"Product": order.Items[i].Sku,
"Quantity": parseInt(order.Items[i].Quantity),
"Price": parseFloat(order.Items[i].UnitPrice)
});
}
Huh surprising !!!
JSON.Stringify() Solved the issue, It turns out the object was not a flat JSON object like I expected but some other object that did not allow me to just access the values