How can I pass a condition into my function? - javascript

this is my function:
I want to pass a condition to change my "selectedConformityStatus" in line 7.
const externalFilter = function () {
if (!__externalFilter) {
__externalFilter = {
gridApi: undefined,
selectedSubjects: [],
selectedGeneralRequirement: "my_responsibility",
selectedConformityStatus: [
"conforms",
"no_conforms",
"not_applicable",
"initial_status",
],
selectedAnalysisResultStatus: "all",
isExternalFilterPresent: function (params) {
return (
(this.selectedSubjects && this.selectedSubjects.length > 0) ||
this.selectedGeneralRequirement !== "all" ||
this.selectedConformityStatus.length > 0 ||
this.selectedAnalysisResultStatus !== "all"
);
},
doesExternalFilterPass: function (node) {
const systemOperatorId = _.get(this, "loggedUser.systemOperatorId");
let systemOperator_AllRequirements = false,
systemOperator_Requirements = [];
if (systemOperatorId) {
const systemOperatorEntry = _.get(
this.project,
"systemOperators",
[]
).find((s) => _.get(s, "systemOperator._id") === systemOperatorId);
if (systemOperatorEntry) {
systemOperator_AllRequirements =
systemOperatorEntry.allRequirements === "yes";
systemOperator_Requirements =
systemOperatorEntry.requirements || [];
}
}
const subjectCondition =
!this.selectedSubjects ||
this.selectedSubjects.length === 0 ||
this.selectedSubjects.includes(
_.get(
node,
"data.dataOverride.subject._id",
_.get(
node,
"data.dataOverride.subject",
_.get(node, "data.requirement.subject._id")
)
)
);
const generalRequirementCondition =
!this.selectedGeneralRequirement ||
this.selectedGeneralRequirement === "all" ||
(this.selectedGeneralRequirement === "my_responsibility" &&
(systemOperator_AllRequirements === true ||
systemOperator_Requirements.some(
(r) =>
_.get(node, "data.requirement.generalRequirement._id") ===
r._id
))) ||
_.get(node, "data.requirement.generalRequirement._id") ===
this.selectedGeneralRequirement;
const conformityStatusCondition =
!this.selectedConformityStatus ||
this.selectedConformityStatus.length === 0 ||
this.selectedConformityStatus.includes(
_.get(node, "data.conformityStatus")
);
const conformityAnalysisResultStatus =
!this.selectedAnalysisResultStatus ||
this.selectedAnalysisResultStatus === "all" ||
(this.selectedAnalysisResultStatus === "all_awainting_analysis" &&
[
"awaiting_analysis",
"awaiting_correction",
"awaiting_review",
].includes(_.get(node, "data.currentStatus"))) ||
_.get(node, "data.currentStatus") ===
this.selectedAnalysisResultStatus;
return (
subjectCondition &&
generalRequirementCondition &&
conformityStatusCondition &&
conformityAnalysisResultStatus
);
},
setGridApi: function (params) {
if (params && params.gridApi) {
this.gridApi = params.gridApi;
}
},
onChangeSubjects: function (subjects) {
this.selectedSubjects = subjects || [];
this.onFilterChanged();
},
onChangeGeneralRequirement: function (item) {
this.selectedGeneralRequirement = item && item.value;
this.onFilterChanged();
},
onChangeConformityStatus: function (value) {
this.selectedConformityStatus = value;
this.onFilterChanged();
},
onChangeAnalysisResultStatus: function (item) {
this.selectedAnalysisResultStatus = item && item.value;
this.onFilterChanged();
},
onFilterChanged: function (item) {
if (this.gridApi) {
this.gridApi.onFilterChanged();
}
},
};
}
return __externalFilter;
};
I want to pass a condition to change my "selectedConformityStatus" in line 7.
Like,
if (__checklist.project.analysisData?.actionPlan == 'yes') {
let selectedConformityStatus: [
"conforms",
"no_conforms",
"not_applicable",
"initial_status",
]
} else {
selectedConformityStatus: [
"conforms",
"no_conforms",
"not_applicable"
]
}
I allready tried like that, pass the condition with the !__externalFilter), but the project brokes.
const externalFilter = function () {
if (!__externalFilter && __checklist.project.analysisData?.actionPlan == 'yes') {
__externalFilter = {
gridApi: undefined,
selectedSubjects: [],
selectedGeneralRequirement: "my_responsibility",
selectedConformityStatus: [
"conforms",
"no_conforms",
"not_applicable",
"initial_status",
],
selectedAnalysisResultStatus: "all",
isExternalFilterPresent: function (params) {
return (
(this.selectedSubjects && this.selectedSubjects.length > 0) ||
this.selectedGeneralRequirement !== "all" ||
this.selectedConformityStatus.length > 0 ||
this.selectedAnalysisResultStatus !== "all"
);
},
doesExternalFilterPass: function (node) {
const systemOperatorId = _.get(this, "loggedUser.systemOperatorId");
let systemOperator_AllRequirements = false,
systemOperator_Requirements = [];
if (systemOperatorId) {
const systemOperatorEntry = _.get(
this.project,
"systemOperators",
[]
).find((s) => _.get(s, "systemOperator._id") === systemOperatorId);
if (systemOperatorEntry) {
systemOperator_AllRequirements =
systemOperatorEntry.allRequirements === "yes";
systemOperator_Requirements =
systemOperatorEntry.requirements || [];
}
}
const subjectCondition =
!this.selectedSubjects ||
this.selectedSubjects.length === 0 ||
this.selectedSubjects.includes(
_.get(
node,
"data.dataOverride.subject._id",
_.get(
node,
"data.dataOverride.subject",
_.get(node, "data.requirement.subject._id")
)
)
);
const generalRequirementCondition =
!this.selectedGeneralRequirement ||
this.selectedGeneralRequirement === "all" ||
(this.selectedGeneralRequirement === "my_responsibility" &&
(systemOperator_AllRequirements === true ||
systemOperator_Requirements.some(
(r) =>
_.get(node, "data.requirement.generalRequirement._id") ===
r._id
))) ||
_.get(node, "data.requirement.generalRequirement._id") ===
this.selectedGeneralRequirement;
const conformityStatusCondition =
!this.selectedConformityStatus ||
this.selectedConformityStatus.length === 0 ||
this.selectedConformityStatus.includes(
_.get(node, "data.conformityStatus")
);
const conformityAnalysisResultStatus =
!this.selectedAnalysisResultStatus ||
this.selectedAnalysisResultStatus === "all" ||
(this.selectedAnalysisResultStatus === "all_awainting_analysis" &&
[
"awaiting_analysis",
"awaiting_correction",
"awaiting_review",
].includes(_.get(node, "data.currentStatus"))) ||
_.get(node, "data.currentStatus") ===
this.selectedAnalysisResultStatus;
return (
subjectCondition &&
generalRequirementCondition &&
conformityStatusCondition &&
conformityAnalysisResultStatus
);
},
setGridApi: function (params) {
if (params && params.gridApi) {
this.gridApi = params.gridApi;
}
},
onChangeSubjects: function (subjects) {
this.selectedSubjects = subjects || [];
this.onFilterChanged();
},
onChangeGeneralRequirement: function (item) {
this.selectedGeneralRequirement = item && item.value;
this.onFilterChanged();
},
onChangeConformityStatus: function (value) {
this.selectedConformityStatus = value;
this.onFilterChanged();
},
onChangeAnalysisResultStatus: function (item) {
this.selectedAnalysisResultStatus = item && item.value;
this.onFilterChanged();
},
onFilterChanged: function (item) {
if (this.gridApi) {
this.gridApi.onFilterChanged();
}
},
};
} else {
__externalFilter = {
gridApi: undefined,
selectedSubjects: [],
selectedGeneralRequirement: "my_responsibility",
selectedConformityStatus: [
"conforms",
"no_conforms",
"not_applicable",
],
selectedAnalysisResultStatus: "all",
isExternalFilterPresent: function (params) {
return (
(this.selectedSubjects && this.selectedSubjects.length > 0) ||
this.selectedGeneralRequirement !== "all" ||
this.selectedConformityStatus.length > 0 ||
this.selectedAnalysisResultStatus !== "all"
);
},
doesExternalFilterPass: function (node) {
const systemOperatorId = _.get(this, "loggedUser.systemOperatorId");
let systemOperator_AllRequirements = false,
systemOperator_Requirements = [];
if (systemOperatorId) {
const systemOperatorEntry = _.get(
this.project,
"systemOperators",
[]
).find((s) => _.get(s, "systemOperator._id") === systemOperatorId);
if (systemOperatorEntry) {
systemOperator_AllRequirements =
systemOperatorEntry.allRequirements === "yes";
systemOperator_Requirements =
systemOperatorEntry.requirements || [];
}
}
const subjectCondition =
!this.selectedSubjects ||
this.selectedSubjects.length === 0 ||
this.selectedSubjects.includes(
_.get(
node,
"data.dataOverride.subject._id",
_.get(
node,
"data.dataOverride.subject",
_.get(node, "data.requirement.subject._id")
)
)
);
const generalRequirementCondition =
!this.selectedGeneralRequirement ||
this.selectedGeneralRequirement === "all" ||
(this.selectedGeneralRequirement === "my_responsibility" &&
(systemOperator_AllRequirements === true ||
systemOperator_Requirements.some(
(r) =>
_.get(node, "data.requirement.generalRequirement._id") ===
r._id
))) ||
_.get(node, "data.requirement.generalRequirement._id") ===
this.selectedGeneralRequirement;
const conformityStatusCondition =
!this.selectedConformityStatus ||
this.selectedConformityStatus.length === 0 ||
this.selectedConformityStatus.includes(
_.get(node, "data.conformityStatus")
);
const conformityAnalysisResultStatus =
!this.selectedAnalysisResultStatus ||
this.selectedAnalysisResultStatus === "all" ||
(this.selectedAnalysisResultStatus === "all_awainting_analysis" &&
[
"awaiting_analysis",
"awaiting_correction",
"awaiting_review",
].includes(_.get(node, "data.currentStatus"))) ||
_.get(node, "data.currentStatus") ===
this.selectedAnalysisResultStatus;
return (
subjectCondition &&
generalRequirementCondition &&
conformityStatusCondition &&
conformityAnalysisResultStatus
);
},
setGridApi: function (params) {
if (params && params.gridApi) {
this.gridApi = params.gridApi;
}
},
onChangeSubjects: function (subjects) {
this.selectedSubjects = subjects || [];
this.onFilterChanged();
},
onChangeGeneralRequirement: function (item) {
this.selectedGeneralRequirement = item && item.value;
this.onFilterChanged();
},
onChangeConformityStatus: function (value) {
this.selectedConformityStatus = value;
this.onFilterChanged();
},
onChangeAnalysisResultStatus: function (item) {
this.selectedAnalysisResultStatus = item && item.value;
this.onFilterChanged();
},
onFilterChanged: function (item) {
if (this.gridApi) {
this.gridApi.onFilterChanged();
}
},
};
}
return __externalFilter;
};
I guess it's pretty simple, but I'm not beeing able to figure out.

You can just create an array and declare its value in your condition
let selectedConformityStatusArray: [];
if (__checklist.project.analysisData?.actionPlan == 'yes') {
selectedConformityStatusArray: [
"conforms",
"no_conforms",
"not_applicable",
"initial_status",
]
} else {
selectedConformityStatusArray: [
"conforms",
"no_conforms",
"not_applicable"
]
}
then in your code just add the array to your selectedConformityStatus key as value
gridApi: undefined,
selectedSubjects: [],
selectedGeneralRequirement: "my_responsibility",
selectedConformityStatus: selectedConformityStatusArray,

Related

Cannot convert undefined or null to object or not length

If you put a value in every input, it works normally. However, errors appear even if only one input is empty.
nameValue.length, an error appears that you cannot work on the length.
Object.values(nameValue).length, the error 'Cannot convert undefined or null to object' appears.
const [values, setValues] = useState({
nameValue: '',
numberValue: '',
contentValue: '',
});
const { nameValue, numberValue, contentValue } = values;
const handleNumber = e => {
const { value, name } = e.target;
setValues({
...values,
[name]: value,
});
};
useEffect(() => {
if (numberValue.length === 11) {
setValues({
numberValue: numberValue.replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3'),
});
} else if (numberValue.length === 13) {
setValues({
numberValue: numberValue
.replace(/-/g, '')
.replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3'),
});
}
}, [numberValue]);
const handleSend = e => {
e.preventDefault();
//console.log(typeof stringify(nameValue) === 'undefined');
const nameValueTrue =
Object.values(nameValue).length > 4 ||
Object.values(nameValue).length < 1 ||
typeof nameValue !== 'string' ||
typeof nameValue === 'undefined';
const numberValueTrue =
Object.values(numberValue).length < 13 ||
Object.values(numberValue).length > 14;
const contentValueTrue =
typeof contentValue !== 'string' ||
Object.values(contentValue).length < 2;
const error = !e.target.value;
if (nameValueTrue) {
alert('이름을 확인해주세요.');
console.log('name안');
} else if (numberValueTrue) {
console.log('number');
alert('휴대폰번호를 확인해주세요.');
} else if (contentValueTrue) {
console.log('content');
alert('내용을 확인해주세요.');
} else {
goto();
}
};
<ContentBox>
<div>Name</div>
<ContentInput
name="nameValue"
value={nameValue || undefined}
//value={nameValue || ''}
//value={nameValue}
onChange={handleNumber}
/>
</ContentBox>
<ContentBox>
<div>Phone Number</div>
<ContentInput
name="numberValue"
value={numberValue || undefined}
//value={numberValue || ''}
//value={numberValue}
onChange={handleNumber}
/>
</ContentBox>
<ContentBox>
<div>Content</div>
<ContentInput
placeholder="내용 입력."
name="contentValue"
value={contentValue || undefined}
//value={contentValue || ''}
//value={contentValue}
onChange={handleNumber}
/>
</ContentBox>
<Submit onClick={handleSend}>Send</Submit>
In your useEffect, you're overwriting the whole values object to just be numberValue. You need to spread the object there too, like you have in handleNumber

Remove sorting in js

How to remove sorting from this script part:
getFirstAvailablePeriod() {
const sortedPeriods = this.periods.sort((a: IPeriod, b: IPeriod) => {
if (a.default_price.price === b.default_price.price) {
return 0;
}
return (a.default_price.price > b.default_price.price) ? 1 : -1;
}).filter((period: IPeriod) => !period.locked);
const alreadySelected: IPeriod = sortedPeriods.find((period: IPeriod) => period.id === this.value);
if (alreadySelected) {
return alreadySelected;
}
return sortedPeriods[0];
},
async getPeriods() {
const params: any = {};
if (this.place === 'familyGrave' && this.type === 'multi') {
params.funeral_id = this.item.funeralId;
}
await getPeriods(this.place, this.type, params).then((periods: IPeriod[]) => {
this.periods = periods.sort((period: IPeriod, prev: IPeriod) => {
if (period.sort === prev.sort) {
return 0;
}
return period.sort - prev.sort;
}).filter((period: IPeriod) => {
return !((user()?.role || 'guest') !== 'super-admin' && !this.allowFree && `${period.default_price.price}` === '0');
});
if (!this.value) {
this.$nextTick(() => {
this.handleSelection(this.getFirstAvailablePeriod());
});
}
});
},
This script part reorder Periods from API. Plaese help me to remove rorting Periods from this script. My JS knownleadge is very bad.
Thanks
In getFirstAvailablePeriod instead of
const sortedPeriods = this.periods.sort((a: IPeriod, b: IPeriod) => {
if (a.default_price.price === b.default_price.price) {
return 0;
}
return (a.default_price.price > b.default_price.price) ? 1 : -1;
}).filter((period: IPeriod) => !period.locked);
try this
const sortedPeriods = [...this.periods].sort((a: IPeriod, b: IPeriod) => {
if (a.default_price.price === b.default_price.price) {
return 0;
}
return (a.default_price.price > b.default_price.price) ? 1 : -1;
}).filter((period: IPeriod) => !period.locked);
And to remove all sortings, delete sorting in getPeroids
this.periods = periods.filter((period: IPeriod) => {
return !((user()?.role || 'guest') !== 'super-admin' && !this.allowFree && `${period.default_price.price}` === '0');
});
Remove this part
.sort((period: IPeriod, prev: IPeriod) => {
if (period.sort === prev.sort) {
return 0;
}
Removed sorting. Give it a try.
getFirstAvailablePeriod() {
const availablePeriods = this.periods.filter((period: IPeriod) => !period.locked);
const alreadySelected: IPeriod = availablePeriods.find((period: IPeriod) => period.id === this.value);
if (alreadySelected) {
return alreadySelected;
}
return availablePeriods[0];
},
async getPeriods() {
const params: any = {};
if (this.place === 'familyGrave' && this.type === 'multi') {
params.funeral_id = this.item.funeralId;
}
await getPeriods(this.place, this.type, params).then((periods: IPeriod[]) => {
this.periods = periods.filter((period: IPeriod) => {
return !((user()?.role || 'guest') !== 'super-admin' && !this.allowFree && `${period.default_price.price}` === '0');
});
if (!this.value) {
this.$nextTick(() => {
this.handleSelection(this.getFirstAvailablePeriod());
});
}
});
},

How to cycle through and then save products?

Good afternoon, I am trying to change the remainder of the product in mongoose in a loop. But persistence doesn't work. I would be grateful for your help!
const statusOutOfStock = await ProductStockStatus.findOne({
color: 'danger',
})
for await (const product of Product.find()) {
const orderItems = order.orderItems.filter(
item => String(item.product) === String(product._id)
)
if (orderItems?.length > 0) {
orderItems.forEach(async orderItem => {
if (orderItem.varIdx === 0 && product.stock !== null) {
const stockResult = product.stock - orderItem.count
product.stock = stockResult
if (stockResult === 0) product.status = statusOutOfStock._id
} else {
const stockResult =
product.variations[orderItem.varIdx].stock - orderItem.count
product.variations[orderItem.varIdx].stock = stockResult
if (stockResult === 0)
product.variations[orderItem.varIdx].status = statusOutOfStock
}
})
await product.save()
}
}
I was able to solve this problem.
/* Deduction of stock */
const statusOutOfStock = await ProductStockStatus.findOne({
color: 'danger',
})
for await (const product of Product.find()) {
/* Get order items by productID */
const orderItems = order.orderItems.filter(
item => String(item.product) === String(product._id)
)
/* If order items exists */
if (orderItems?.length > 0) {
/* Run of order items and write new stock */
const proDb = await Product.findById(product._id)
let buffer = []
await Promise.all(
orderItems.map(async orderItem => {
if (orderItem.varIdx === 0 && product?.stock !== null) {
const stockResult = product.stock - orderItem.count
proDb.stock = stockResult < 0 ? 0 : stockResult
if (stockResult === 0) proDb.status = statusOutOfStock._id
} else if (
!!product?.variations[orderItem.varIdx]?.stock !== null &&
orderItem.varIdx !== 0
) {
const stockResult =
product.variations[orderItem.varIdx].stock - orderItem.count
if (buffer?.length === 0) buffer = [...product.variations]
buffer[orderItem.varIdx].stock =
stockResult < 0 ? 0 : stockResult
proDb.variations = buffer
if (stockResult === 0)
proDb.variations[orderItem.varIdx].status = statusOutOfStock
}
})
)
await proDb.save()
}
}

"something went wrong" error on fucntion getfloat

This code works perfectly beside the last part , and I do not see where might be the error. I tested it, and the main problem is in Trade.prototype.getFloat maybe is the callback idk, (the Trade.prototype.getFloat I got it from a 3y post here on stack from other user).
3y problem: This code works perfectly besides this line: "inventory[asset.assetid].floatvalue = getFloat". As you can see it is situated in async mode, and this line initializes a request to get some value, but it cant get it couse value is undefined. I tested it, and the main problem in request, which is asynchronous too. So the answer is how to stop the async mode and wait the return of the request.
'use strict'
const config = require('../config')
const request = require('request')
const async = require('async')
const Trade = require('./index')
const MAX_RETRIES = 3
const API_URL = 'https://api.steamapis.com/steam/inventory'
Trade.prototype.getInventory = function getInventory(steamID64, appID, contextID, callback, retries) {
request(`${API_URL}/${steamID64}/${appID}/${contextID}?api_key=${config.SteamApisKey}`, (error, response, body) => {
if (!error && response.statusCode === 200) {
const items = JSON.parse(body)
const assets = items.assets
const descriptions = items.descriptions
const inventory = {}
if (descriptions && assets) {
async.forEach(descriptions, (description, cbDesc) => async.forEach(assets, (asset, cbAsset) => {
if (
description.classid !== asset.classid ||
!description.tradable ||
!description.marketable ||
description.market_hash_name.indexOf('Souvenir') > -1
) {
return cbAsset()
}
if (typeof inventory[asset.assetid] !== 'undefined') {
return cbAsset()
}
const type = Trade.prototype.getItemType(description.market_hash_name, description.type)
const wear = Trade.prototype.getItemWear(description.market_hash_name)
const inspect = Trade.prototype.getInspect(steamID64, asset.assetid, description.actions)
const getFloat = Trade.prototype.getFloat(inspect, asset.assetid, function(_float){
var data = String(_float);
inventory[asset.assetid].floatvalue = data;
inventory[asset.assetid] = asset
inventory[asset.assetid].item_type = type
inventory[asset.assetid].item_wear = wear
inventory[asset.assetid].inspect = inspect
inventory[asset.assetid].data = {
background: description.background_color,
image: description.icon_url,
tradable: description.tradable,
marketable: description.marketable,
market_hash_name: description.market_hash_name,
type: description.type,
color: description.name_color,
};
return cbAsset();
})
}));
}
return callback(null, inventory)
}
let retry = retries
if (typeof retries === 'undefined') {
retry = 0
}
retry += 1
if (retry <= MAX_RETRIES) {
return Trade.prototype.getInventory(steamID64, appID, contextID, callback, retry)
}
let statusCode = null
if (typeof response !== 'undefined' && typeof response.statusCode !== 'undefined') {
statusCode = response.statusCode
}
return callback({ error, statusCode })
})
}
Trade.prototype.getInventories = function getInventories(params, callback) {
const inventories = {}
async.each(params, (user, cb) => {
Trade.prototype.getInventory(user.steamID64, user.appID, user.contextID, (err, data) => {
inventories[user.id] = {}
inventories[user.id] = {
error: err,
items: (!err) ? Object.keys(data).map(key => data[key]) : null,
}
cb()
})
}, () => {
callback(inventories)
})
}
Trade.prototype.getItemType = function getItemType(marketHashName, type) {
if (marketHashName.indexOf('Key') !== -1) {
return { value: 0, name: 'key' }
}
if (marketHashName.indexOf('★') !== -1) {
return { value: 1, name: 'knife' }
}
if (
type.indexOf('Classified') !== -1 ||
type.indexOf('Contraband') !== -1 ||
type.indexOf('Covert') !== -1
) {
return { value: 2, name: 'rare_skin' }
}
if (
type.indexOf('Consumer Grade') !== -1 ||
type.indexOf('Base Grade') !== -1 ||
type.indexOf('Graffiti') !== -1 ||
type.indexOf('Sticker') !== -1 ||
type.indexOf('Industrial Grade') !== -1
) {
return { value: 4, name: 'misc' }
}
return { value: 3, name: 'weapon' }
}
Trade.prototype.getItemWear = function getItemWear(marketHashName) {
if (marketHashName.indexOf('Factory New') !== -1) {
return 'FN'
}
if (marketHashName.indexOf('Minimal Wear') !== -1) {
return 'MW'
}
if (marketHashName.indexOf('Field-Tested') !== -1) {
return 'FT'
}
if (marketHashName.indexOf('Well-Worn') !== -1) {
return 'WW'
}
if (marketHashName.indexOf('Battle-Scarred') !== -1) {
return 'BS'
}
return false
}
Trade.prototype.getInspect = function getInspect (steamID64, assetid, actions) {
let inspectLink = null;
if (actions) {
for (const a in actions) {
if (actions[a].name.indexOf('Inspect') !== -1) {
inspectLink = actions[a].link
inspectLink = inspectLink.replace('%owner_steamid%', steamID64)
inspectLink = inspectLink.replace('%assetid%', assetid)
}
}
}
return inspectLink
}
Trade.prototype.getFloat = function getFloat (adding, callback) {
request ("https://api.csgofloat.com:1738/?url=" + adding, (error, response, body) => {
if (!error && response.statusCode == 200) {
var floatBody = JSON.parse(body);
var float = floatBody["iteminfo"]["floatvalue"];
var id = id;
if (float != "") {
callback(float);
} else {
return "wrong";
}
} else {
console.log('something goes wrong');
return "wrong";
}
});
}

React - useState only affecting last property value

I'm trying to set validPassword and validFormData values to false whenever a form is submited and the values are empty. I'm calling this function on submit but it's only changing the last property in my useState
const [validPassword, setValidPassword] = useState({
password: true,
confirmPassword: true
})
const [validFormData, setValidFormData] = useState({
email: true,
name: true,
lastName: true,
phone: true,
})
const signupAction = (e) => {
e.preventDefault()
if (formData.email === "" || formData.name === "" || formData.lastName === "" || formData.phone === "" || formData.password === "" || formData.confirmPassword === "") {
for (let p in formData) {
if (formData[p] === "") {
if (p === "password" || p === "confirmPassword") {
setValidPassword({ ...validPassword, [p]: false })
} else {
setValidFormData({ ...validFormData, [p]: false })
}
}
}
} else {
console.log('success')
}
/* signup(formData, history) */
}
What I get from this is:
validPassword = {
password: true,
confirmPassword: false
}
validFormData = {
email: true,
name: true,
lastName: true,
phone: false,
}
The setState function is async. The common pattern of setting a state which is the one you are using is not fool proof one. One should use callback based setting state to by pass these common issues. Code like below would work
const signupAction = (e) => {
e.preventDefault()
if (formData.email === "" || formData.name === "" || formData.lastName === "" || formData.phone === "" || formData.password === "" || formData.confirmPassword === "") {
for (let p in formData) {
if (formData[p] === "") {
if (p === "password" || p === "confirmPassword") {
setValidPassword((prevState) => ({...prevState, [p]: false }))
} else {
setValidFormData((prevState) => ({ ...prevState, [p]: false }))
}
}
}
} else {
console.log('success')
}
/* signup(formData, history) */
}
Further, to prevent multiple updates, it is best if you store the changes in the loop in a local variable and set all at once like below
const signupAction = (e) => {
e.preventDefault()
if (formData.email === "" || formData.name === "" || formData.lastName === "" || formData.phone === "" || formData.password === "" || formData.confirmPassword === "") {
const tempValidPassword = { ...validPassword};
const tempValidFormData = { ...validFormData};
for (let p in formData) {
if (formData[p] === "") {
if (p === "password" || p === "confirmPassword") {
tempValidPassword[p] = false;
} else {
tempValidFormData[p] = false;
}
}
}
setValidPassword(tempValidPassword);
setValidFormData(tempValidFormData);
} else {
console.log('success')
}
/* signup(formData, history) */
}
Note: These are only pesudo-code. Fit according to your needs. Try to use functional updates to state as mentioned here whenever possible

Categories

Resources