wants to null values after api response is true - react-native

i want to clear my all text field when i post data to server and response become true here is my code of function where i post my data to API and its response exactly as i want but i want when response true all text field are clear..
updateProfile(){
axios.post( "http://172.104.217.178/api/update_sponsor_profile/"+this.state.UserId,{
name:this.state.name,
username:this.state.username,
address:this.state.address,
country_id:this.state.getCountryId,
state_id:this.state.getStateId,
city_id:this.state.getCityid,
} )
.then(response => {
alert(JSON.stringify(response));
if(response.data.status===1){
this.setState({name:null,username:null,address:null,getCountryId:null,getStateId:null,getCityid:null})
}
})
.catch(error => alert(error.response.data));
}
here is the code of my text fields
updateValue(text,field){
if(field==='name'){
this.setState({name:text})
}
else if(field==='username'){
this.setState({username:text})
}
else if(field==='address'){
this.setState({address:text})
}
}

While you may clear your state correctly the input field doesn't take its value from your state, it just updates it when you input something so clearing the state doesn't affect it at all. Try setting the Input field like this:
<Input
onChangeText={(text) => this.updateValue(text,'address')}
value={this.state.address}
/>
the value prop is inheritted from the native TextInput, its documentation is here.

Related

loadOptions getting called for same string which was searched earlier and cacheOptions is enabled

I am trying to use AsyncSelect from react-select library.
I have enabled cacheOptions option.
Using below mentioned steps I am seeing an issue with loadOptions
Search for a string test
List of options gets displayed
Clear the input field
Enter same string again test
Immediately displays same list of options
loadOptions fires an API with search input tes
Clear the input field
Enter same string again test
Immediately displays same list of options
loadOptions fires API with search input te.
I am not sure why loadOptions getting fired in this scenario if I am entering the same search string.
Here is the AsyncSelect
<AsyncSelect
classNamePrefix="select-item"
onChange={ onOptionSelect }
getOptionValue={ item => item.id }
placeholder="Search by Item"
formatOptionLabel={ company => <CompanyWithIcon Item={ Item } /> }
loadOptions={ loadOptions }
styles={ customStyles }
isSearchable
cacheOptions
isClearable
/>
Here is the loadOptions function
const loadOptions = inputValue => searchItem(inputValue);
Can anybody please help?
I think it is happening because you are not using a callback or a promise for loadOptions. The loadOptions should return a promise.
Reference doc -> https://react-select.com/props#async-props says:
loadOptions:
Function that returns a promise, which is the set of options to be used once the promise resolves.
It should be like below:
const loadOptions = (inputValue, callback) => {
setTimeout(() => {
callback(searchItem(inputValue));
}, 1000);
};

How can I bind to an array on my input using Vuetify/Vue.js?

I am using Vuetify.js on a project and everything is working very well. I am trying to add some custom error messages to my username input. For example, if a user trying to sign in is not found - I want to display that message.
I am able to pass a single value using :error-messages="errors.myMessage. Works great!
However, I'd like to set multiple values to that error message. For example, if:
The user is not found
The user does not have permission
???
Here is what I am doing that works:
...
type="email"
:error-messages="errors.userNotFoundException"
v-model="form.username"
...
According to the Vuetifyjs docs, I can pass a string or an array to :error-messages. Looking through the playground, I've tried this:
...
type="email"
:error-messages="[errors.userNotFoundException, errors.notAuthorizedException]"
v-model="form.username"
...
However, when the page renders, the username field is showing as invalid & no errors are showing. Ideally, I'd like to show different messages based on the error that is returned on the same input. An array make sense here...
To set the values, I am doing this based on my Axios response:
data() {
return {
errors: {
notAuthorizedException: '',
userNotFoundException: '',
},
},
...
.catch(error => {
console.log("error: ", error);
if (error.code === 'NotAuthorizedException') {
this.errors.userNotFoundException = error.message;
}
...
What is the correct way to show multiple message(s) for the same input? Thank you for any suggestions!
I believe a single error message is the way to go. You can simply change it based on what the axios error is.
type="email"
:error-messages="loginError"
js:
data() {
return {
loginError: ''
}
},
...
.catch(error => {
console.log("error: ", error);
this.loginError = error;
...

How to append additional text when making a POST request?

I got a Vue app with an input text field in a form where the user can type a new name for a branch. The user can also click a checkbox to designate whether a branch is active or inactive. Then, he submits the form via a submit button which then sends a POST (or PUT if he is editing the existing data) request to a remote data API.
Demo screenshot:
My question: I need to append the text (inactive) to the branch name when it is submitted to the server if the active checkbox is not selected, but also need to remove that inactive text if it exists and the active checkbox is left unchecked:
Hypothetical branch name with inactive flag and checkbox not checked:
ABCD (inactive)
Hypothetical branch name if active checkbox checked:
ABCD
Here is sample code for my POST method:
onSubmitAdd() {
this.loading = true
ApiService.postBranch(this.branch)
.then(() => {
this.loading = false
this.$router.push({ path: '/branches' })
})
.catch(err => {
if (err.response) {
this.errors = err.response.data
} else {
if (err.request) {
this.errors = err.request
} else {
this.errors = err.message
}
}
this.loading = false
console.error('Error from post', err)
})
}
Thanks for any tips you can provide for the logic to make this happen!
Add a v-model with your checkbox and based on that input you can decide whether to add or not the inactive text in your onSubmitAdd function
The conditional text is not appended when sending the post request. You have already set the state to be active or inactive (and of course your Api is expecting to read a boolean value e.g "branchStatus": boolean).
You set the conditional when you are retrieving the information with a get request which will return JSON data that should contain the state. You can then set the display text based on the state.
let displayStatus = ''
response.branchStatus ? displayStatus = "active" : displayStatus = "inactive"

Using Vue, how can I remove elements from the screen after they have been deleted?

I am learning Vue, and I have a list of todo items that has a checkbox that I am able to mark as complete. Everything in my application is working.
When I check the checkbox, I am adding items to the completedItems array. When unchecked, I am removing items. I am able to check the array length and it is also correct.
I have a button that I can click that will remove all items marked as complete from my list.
The overarching logic is working fine. The status of being marked as complete is working, and the actual record is getting deleted as expected.
However, I am unable to remove the item from the actual view. I am not sure what I am doing wrong -- incorrectly updating my completedItems array or something. The items that I delete will only disappear after a full page refresh.
Here is what I am doing:
<task v-for="item in list.items">...</task>
...
data() {
return {
completedItems: [],
}
},
props: ['list'],
...
axios.delete(...)
.then((response) => {
if (response.status === 204) {
this.completedItems = this.completedItems.filter(i => i !== item);
} else {
console.error('Error: could not remove item(s).', response);
}).catch((error) => {
alert(error);
});
Thank you for any suggestions!
EDIT
Here is how I am checking for a match now, and it is coming across correctly, the element in the array still isn't getting removed from the page.
this.completedItems = this.completedItems.filter(i => i.id !== item.data.id);
// i.id = 123
// item.data.id = 123
You should avoid manipulating props directly, since props are supplied by the parent component and can be changed without notice. I would do something like this:
data(){
return{
completedItems[],
localList: this.list
}
}
Then, manipulate and bind the localList array instead of the prop, this should give you what you are looking for.

Aurelia - Custom validation to check if a form has changes

I see THIS question regarding whether the form I am validating has changed.
However it has nothing to do with Aurelia validation and I would like to validate whether the form has any changes upon clicking the save button. I dont want to do it on the server.
What I have done is to save the values I fetched initially so I can do a comparison.
fetch("/api/Client/editClient/" + parms.id, {
method: "GET",
headers
})
.then(response => response.json())
.then(data => {
this.client.deserialize(data);
this.originalClient === this.client;
})
original client is the unmodified object.
I have created a custom validation function however its not working as intended.
I thought I could use the current value and then compare it to the original value.
ValidationRules.customRule(
'changesExist',
(value, obj, fetchedEntity) =>
fetchedEntity != value,
'No changes detected'
);
When I try and use it I find it erroring:
// Validation Rules.
ValidationRules
.ensure(a: ClientDetails) => a).satisfiesRule('changesExist', this.originalClient);
I am unsure how to make this work. What I want is a validation that compares the orginalClient object with the the one that is to be sent back to the server. This way I can check if there is reason for sending it back can saving it to the database...
It's rather brute force, but this will likely do what you want:
JSON.stringify(fetchedEntity) !== JSON.stringify(value)
The app-contacts sample app does it using an areEqual function. Have a look at the repo and you can see how it's used and how you could adapt it for your purposes.
function areEqual(obj1, obj2) {
return Object.keys(obj1).every((key) => obj2.hasOwnProperty(key) && (obj1[key] === obj2[key]));
};