I am new to react js , here
this.state = {
technologies: [],
showLowError: false,
showHighError: false,
showMediumError: false
}
I have this state variables.
Now,
What I am trying to do is ,
if(type === "Low") {
errorState = "showLowError";
} else if(type === "Medium") {
errorState = "showMediumError";
} else {
errorState = "showHighError";
}
if (tobeupdated === "count") {
let validateData = this.validate(type, noc);
console.log("validateData is ==>", validateData);
this.setState({
[errorState]: validateData
})
}
update the state, depend upon some variables, Now,
[errorState] is not updating the exact value, Value for the state is not getting set.can any one help me with this ?
try adding:
this.setState(this.state);
after:
this.setState({
[errorState]: validateData
})
Related
everyone. I have a problem that arises after changing excluding params. I use Redux to save all params data but I have an incomprehensible error. I add a video that shows that problem. Also, I attach some code parts. All elements are memo. Events are disabled after second param change. video
if (value === "true" || value === "false") {
newValue = value === "true" ? true : false;
}
if (newValue === true && (name === "DU_DT" || name === "SINF")) {
if (name === "DU_DT") {
result = { ...values, DU_DT: true, SINF: false };
} else {
result = { ...values, DU_DT: false, SINF: true };
}
} else {
result = { ...values, [name]: newValue }
}
dispatch({
type: ConfigurationActions.SET_VALUES,
payload: result,
});
My problem is that I want to insert values that are not repeated when doing a push
This is my code :
addAddress: function() {
this.insertAddresses.Adress = this.address_address
this.insertAddresses.State = this.selectedStateAddress
this.insertAddresses.City = this.selectedCityAddress
if(this.insertAddresses.Adress !== "" && this.insertAddresses.State !== null && this.insertAddresses.City !== null) {
let copia = Object.assign({}, this.insertAddresses);
this.addresses.push(copia)
}
else
{
this.$message.error('Not enough data to add');
return
}
},
When adding a new element to my object, it returns the following.
When I press the add button again, it adds the same values again, I want to perform a validation so that the data is not the same. How could I perform this validation in the correct way?
Verify that the item doesn't already exist in the array before inserting.
You can search the array using Array.prototype.find:
export default {
methods: {
addAddress() {
const newItem = {
Address: this.address_address,
State: this.selectedStateAddress,
City: this.selectedCityAddress
}
this.insertItem(newItem)
},
insertItem(item) {
const existingItem = this.addresses.find(a => {
return
a.State === item.State
&& a.City === item.City
&& a.Address === item.Address
})
if (!existingItem) {
this.addresses.push(item)
}
}
}
}
On the other hand, if your app requires better performance (e.g., there are many addresses), you could save a separate dictonary to track whether the address already exists:
export default {
data() {
return {
seenAddresses: {}
}
},
methods: {
insertItem(item) {
const { Address, State, City } = item
const key = JSON.stringify({ Address, State, City })
const seen = this.seenAddresses[key]
if (!seen) {
this.seenAddresses[key] = item
this.addresses.push(item)
}
}
}
}
demo
check it:
let filter= this.addresses.find(x=> this.insertAddresses.State==x.State)
if (filter==null) {
this.$message.error('your message');
}
OR FILTER ALL
let filter= this.addresses.find(x=> this.insertAddresses.Adress==x.Adress && this.insertAddresses.State==x.State && this.insertAddresses.City==x.City)
if (filter==null) {
this.$message.error('your message');
}
``
I have a react component with following state
state = {
SandD: true,
Cancellation: false,
Payments: false,
EandR: false,
InternationalShipping: false,
ExpressDelievery: false
}
I want at a time only one selected state to be true and rest to be false. for that I was thinking the following logic
currentActiveState = (value) => {
for ( i=0; i<this.state.length; i++) {
console.log(this.state[i])
if(this.state[i] == value) {
console.log(this.state[i])
} else {
this.setState(this.state[i]: false)
}
}
}
Here value is the property of the state which need to have a value and rest everything should be false..
For example if Payments is true then everything else should be false..
Can someone help me in fixing the above logic or tell me how I can solve it?
Try giving this a shot:
currentActiveState = (value) => {
const newState = {};
Object.keys(this.state).forEach(key => {
newState[key] = key === value;
})
this.setState(newState);
}
I'm trying to build a little chat bot, and I seem to be nearing completion if it were not for this bug. The issue seems to be that my switch statement isn't handling the setState properly.
Uquestion extends React.Component {
constructor(props) {
super(props);
this.state = {
text: this.props.text,
response: "Here is the answer"
}
this.handleChange = this.handleChange.bind(this)
this.key = this.key.bind(this)
this.fetchResponse = this.fetchResponse.bind(this)
}
handleChange(event) {
this.setState({
question: event.target.value
})
}
fetchResponse() {
switch(this.state.searchKey) {
case "BBQ":
this.setState({
response:"Texas BBQ"
})
break;
case "book":
this.setState({
response:"It's close, but probably The Night in Question by Tobias Wolff."
})
break;
case "restaurant":
this.setState({
response:"Andaman, a little Thai spot in Denton, Texas."
})
break;
case "work":
this.setState({
response:"Lots of this and lots of that."
})
break;
case "upbringing":
this.setState({
response:"Texas thunderstorms over endless plains."
})
break;
case "future":
this.setState({
response:"I hope to work on meaningful applications and write meaningful narratives"
})
break;
case "fun":
this.setState({
response:"When the moon is full, I write by candle light."
})
break;
default:
this.setState({
response:"Um, what?"
})
}
}
//this function sets a key that I will later use to fetch a response to the user's question.
key() {
var question=this.state.question;
var questionUpper=question.toUpperCase();
// the is not -1 determines if the phrase appears anywhere in the question.
if(questionUpper.search("FAVORITE FOOD")!==-1) {
this.setState({
searchKey:"BBQ"
}, this.fetchResponse())
}
else if(questionUpper.search("FAVORITE BOOK")!==-1) {
this.setState({
searchKey:"Book"
}, this.fetchResponse())
}
else if(questionUpper.search("FAVORITE RESTAURANT")!==-1) {
this.setState({
searchKey:"Restaurant"
},this.fetchResponse())
}
else if(questionUpper.search("WORK EXPERIENCE")!==-1) {
this.setState({
searchKey:"work"
},this.fetchResponse())
}
else if(questionUpper.search("GROWING UP")!==-1) {
this.setState({
searchKey:"upbringing"
},this.fetchResponse())
}
else if(questionUpper.search("FAVORITE AUTHOR")!==-1) {
this.setState({
searchKey:"author"
},this.fetchResponse())
}
else if(questionUpper.search("FUTURE")!==-1) {
this.setState({
searchKey:"future"
},this.fetchResponse())
}
else if (questionUpper.search("FOR FUN")!==-1) {
this.setState({
searchKey:"fun"
},this.fetchResponse())
}
else {
this.setState({
searchKey:"default"
}, this.fetchResponse())
}
}
render() {
return (
<div>
<p> {this.state.response} </p>
<textarea onChange = {this.handleChange} className="q"> {this.props.text} </textarea>
<button className="a" onClick={this.key}>Ask!</button>
</div>
);
}
}
ReactDOM.render(<Uquestion text="Type Question Here."/>, document.getElementById("content"))
You are passing wrong callback in setState function. And in fetchResponse you've wrote some wrong cases. I've corrected your mistakes, you can see on working example in Codepen
wrong:
this.setState({
searchKey: "book"
}, this.fetchResponse())
correct:
this.setState({
searchKey: "book"
}, this.fetchResponse)
you can read react source code
ReactComponent.prototype.setState = function (partialState, callback){
!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : _prodInvariant('85') : void 0;
this.updater.enqueueSetState(this, partialState);
if (callback) {
this.updater.enqueueCallback(this, callback, 'setState');
}
};
enqueueCallback: function (publicInstance, callback, callerName) {
ReactUpdateQueue.validateCallback(callback, callerName);
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);
if (!internalInstance) {
return null;
}
if (internalInstance._pendingCallbacks) {
internalInstance._pendingCallbacks.push(callback);
} else {
internalInstance._pendingCallbacks = [callback];
}
enqueueUpdate(internalInstance);
}
function enqueueUpdate(internalInstance) {
ReactUpdates.enqueueUpdate(internalInstance);
}
so, I think you the callback is like this:
this.setState({
searchKey:"BBQ"
}, this.fetchResponse)
basically, I am validating form fields by checking if they pass my regex, and if they do, I am setting state with either 'success' or 'error' (used by react-bootstrap).
so basically, I have about 6 functions that need to execute, however, the password field validation functions are giving me a lot of trouble.
My handleSubmit() at the moment looks something like this -
handleSubmit() {
this.validate1();
this.validate2();
// ...
this.validatePassword();
this.validateConfirmPassword();
}
However, the issue is that validatePassword() will setState either 'success' or 'error', and since the functions are not firing off in order, I usually get the wrong result for validateConfirmPassword().
I am reading the mozilla page on Promises, but I am really confused and not sure how to apply that in my code.
Could I do something like Promise.all([everything_except_validateConfirmPassword]).then(validateConfirmPassword()) but that doesn't seem right..
validatePassword(pass) {
if (pass.length >= 8) {
if (checkPass.test(pass)) {
this.setState({
passValidation: validation.success
});
} else {
this.setState({
passValidation: validation.error
});
}
} else {
this.setState({
passValidation: validation.error
});
}
}
validateConfirmPassword(pass, confirmPass) {
const matches = pass === confirmPass;
if (matches && this.state.passValidation === validation.success) {
this.setState({
confirmPassValidation: validation.success
});
} else {
this.setState({
confirmPassValidation: validation.error
});
}
}
You can solve this by using React's componentDidUpdate in this way:
componentDidUpdate() {
if (this.state.canCheckConfirmPwd) {
this.validateConfirmPassword();
}
}
validatePassword(pass) {
if (pass.length >= 8) {
if (checkPass.test(pass)) {
this.setState({
passValidation: validation.success,
canCheckConfirmPwd: true, // on next update we'll trigger validateConfirmPassword()
});
} else {
this.setState({
passValidation: validation.error
});
}
} else {
this.setState({
passValidation: validation.error
});
}
}
validateConfirmPassword(pass, confirmPass) {
const matches = pass === confirmPass;
if (matches && this.state.passValidation === validation.success) {
this.setState({
confirmPassValidation: validation.success,
canCheckConfirmPwd: false, // to avoid retriggering the function on next update
});
} else {
this.setState({
confirmPassValidation: validation.error,
canCheckConfirmPwd: false,
});
}
}