React nattive multi select , cant select multiple values - react-native

I've an api which is resolving into an array of objects, something like this
[
{flagUrl : 'http://....' , name : India , id : 7},
{flagUrl : 'http://....' , name : USA , id : 2},
{flagUrl : 'http://....' , name : Australia , id : 8},
....
]
and then Im using https://www.npmjs.com/package/react-native-select-multiple , this package to make a multi selectable list from above link.
What i want is , firstly I can display the list of country in which user can select lets say two countries ( i can control max select with the prop provided ) and then I want when user goes to next page, I can get what id user has selected in previous screen.
Currently i tried to display the same and its just the list of countries that i can show right now and then I cant get their ids. Here's what i tried so far
<SelectMultiple
items={this.state.countryList.map((x) => x.name)}
selectedItems={this.state.selectedCountries}
onSelectionsChange={this.onSelectionsChange}
maxSelect={2}
/>
where my countrylist has the above array and here are the functions that i've used
onSelectionsChange = (selectedCountries) => {
this.setState({ selectedCountries })
}
and selectedItems is just an empty array in my state.
So I just want to render a list of countries, user selects few of them and then i can send the country's selected ids to the next screen via this.props.navigate...
Let me know if you need additional information on this.
Thanks in advance :)

Your country list must be label and value like
<SelectMultiple
items={this.state.countryList.map((x) => ({ name: x.name, value:x.id })}
selectedItems={this.state.selectedCountries}
onSelectionsChange={this.onSelectionsChange}
maxSelect={2}
/>
the onSelectionsChange method should be the same
onSelectionsChange = (selectedCountries) => {
this.setState({ selectedCountries })
}
Then when you want to move to another screen then
moveToAnotherPage =() => {
const { selectedCountries } = this.state;
const { navigation } = this.props;
const ids = selectedCountries.map(item => item.value);
navigation.navigate('ScreenName', {ids});
}

Related

How do I split up an array while still selecting all items?

Let's say I have an array of fruits and an empty basket array. I push the fruits to the basket and loop through the basket in the template. I can output the whole array of fruits inside the basket.
<template>
<div v-for="fruit in basket">
<li>{{ fruit }}</li>
</div>
<button #click="addFruit">Add to basket</button>
</template>
<script>
data() {
return {
fruits: ['Orange', 'Apple'],
basket: [],
};
},
methods: {
addFruit() {
this.basket.push(this.fruits);
},
}
</script>
But what if I want each individual fruit to be shown as a list item? As it is right now I output the entire array of fruits.
I know that I can easilly get the individual fruits by saying
<li>{{ fruit[0] }}</li>
But that would not be practical as it requires a lot of manual work.
When I am pushing the fruits, I am looking for a way to also split them up, so that when I fire the addFruit function, I add all the fruits, but I add them as individual items.
I know there are other ways to do this, but I specifially want to know how I do this while keeping the arrays and the push method.
EDIT: I tried to write the fruit example because I wanted to keep it as simple as possible, but I will include my own code then.
In my code, I fetch an array of data from my database. I store the data results in a const called recipients. That is then pushed into an array called defaultTags. So I push an array of data into an empty array, in this case a list of emails and other contact information, which is then outputted as a tag, but what I want is to actually output the data as individual items. So instead of having one big tag that stores the whole array. Eg: [email1, email2, email3], I wish to have a seperate tag for each email in the array.
load() {
switch (this.entityType) {
case 'TENANCY':
userService.getCurrentUser().then(userResult => {
tenancyService.getTenants(this.entityId).then(result => {
const defaultTags = [];
const recipients = result.data
.map(tenant => tenant.legalEntity)
.filter(legalEntity => legalEntity.email || (!legalEntity.email && this.asNotification ? legalEntity.name : null))
.map(legalEntity => ({
emailAddress: legalEntity.email || (!legalEntity.email && this.asNotification ? legalEntity.name.concat(' ', `(${this.$t('letterMail').toLowerCase()})`) : null),
legalEntityId: legalEntity.id
}));
if (recipients.length) {
defaultTags.push(this.setText({description: this.$t('tenants'), recipients}));
}
this.autocompleteItems.push(...defaultTags);
if (this.includeUser) {
defaultTags.push(this.setText({
description: this.$t('user'),
recipients: [{emailAddress: userResult.data.email}]
}));
}
if (this.prefill) {
this.tagsChanged(defaultTags);
}
tenancyService.getUnits(this.entityId).then(result =>
result.data.forEach(unitTenancy => this.addPropertyContactsToAutocompleteItems(unitTenancy.unit.propertyId)));
});
});
break;
case 'UNIT':
unitService.get(this.entityId).then(result =>
this.addPropertyContactsToAutocompleteItems(result.data.propertyId));
break;
case 'PROPERTY':
this.addPropertyContactsToAutocompleteItems(this.entityId);
break;
}
},
I am focusing specifically on this line:
if (recipients.length) {
defaultTags.push(this.setText({description: this.$t('tenants'), recipients}));
}
It outputs the entire fruit items because you are pushing the whole array into the basket array, not the actual items. Saying basket is an array of array, not an array of fruits.
// Instead of this
this.basket.push(this.fruits); // [['Orange', 'Apple']]
// Use array destructuring
this.basket.push(...this.fruits); // ['Orange, 'Apple']
// Or concat
this.basket.concat(this.fruits); // ['Orange, 'Apple']

VUEJS and Vuetify - Push the results from a localbase into a data table

How do i push my results into a data object please
I would like to push the :key to the id field and the :data to map across to my other data fields
my data object is called orgs: []
I have the following data returned from my get query
[{…}]
0:
data: {person: 'John', orgName: 'test', due: 'this is due'}
key: "11ed25ccf7548160bff2ab4c1d56ee40"
I have tried
this.$db.collection('orgs').get({ keys: true })
.then
(response => {
console.log('orgs: ', response) <--- this displays the results
this.orgs.forEach(response => {
const data = {
'person': response.data.person,
'orgName': response.data.orgName,
'due': response.data.due,
'id': response.key
}
this.orgs.push(data)
})
});
I get no errors but my this.orgs data item remains empty so assume I am not updating the array for some reason
Thanks
I seem to be able to populate it in a simple way as follows
this.$db.collection('orgs').get({ keys: true })
.then
(response => {
this.orgs = response
console.log('response:', this.orgs)
})
Is there any issue with this approach for just getting my results or should I be using push?

Error in vue-simple-suggest when item is selected

In my vue/cli 4 / Bootstrap 4.3 app I make suggestion component(using vue-simple-suggest)
with some additive parameters and returning data I need to get slug
field of selected row and to redirect to other page
based on this slug. Search works ok for me, but when Item in selection list is selected
I see in browsers console one more request to database with whole selected item object and that
raise error.
I make:
<vue-simple-suggest
id="search_string"
v-model="search_string"
display-attribute="name"
value-attribute="slug"
:list="simpleSuggestionList"
autocomplete=off
mode="select"
#select="taskSuggestionSelected()"
></vue-simple-suggest>
and js code:
simpleSuggestionList() {
let filters={
search_string : this.search_string, // search
only_free : ( this.cbx_only_free ? 1 : 0), // additive parameters
price_min : this.tasksPriceRange[0],
price_max : this.tasksPriceRange[1],
selectedCategories : this.getSelectedCategories
}
console.log('filters::')
console.log(filters)
return axios.post(this.apiUrl + '/tasks-search', filters, this.credentialsConfig)
.then(({data}) => {
return data.tasks
})
.catch(error => {
console.error(error)
this.showPopupMessage('Tasks search', error.response.data.message, 'warn')
})
// return this.retArray
},
taskSuggestionSelected() {
console.log('\'taskSuggestionSelected par1 ::\'+par1 +" search_string::"+this.search_string::')
return false
}
1) Why error and how not to trigger request to server when item is selected and
2) how can I save/ pass slug of selected item into taskSuggestionSelected method as I need to make redirection?
"vue": "^2.6.10",
"vue-simple-suggest": "^1.10.1",
Thanks!

React Native fetch array json data

I am pulling data from Mysql to React native. As you can see, the output of the data I have captured is in the array. How can I pull Array data? With the code below, I can pull the data into an array. For example, I want to extract the new_image variable from the array.
getBusinessNewsData() {
fetch('...').then((response) => response.json())
.then((findresponse)=>{
var newSearch = findresponse.new_image;
console.log(newSearch)
this.setState({
data:newSearch,
})
})
[
{
"id":"..",
"new_date":"...",
"new_title":"...",
"new_slug":"...",
"new_url":"",
"new_image":"...",
"new_fixed":"..."
}
]
Map on the response and extract new_image
const result = findResponse.map((d) => d.new_image);
Then you can set result in component internal state.
If the console.log(newSearch) gives you the array above and you want to have the new_image property then you can set a state like this.setState({ newImage: newSearch[0].new_image })
By doing so this.state.newImage would be the value from the array.

Filter other columns based on first columns

I'm using jquery data tables and I'm assigning an array of values to the initialization of the data table. The table basically looks like this.
based on an an radio button I would like to limit the items that are display in the table and the items that are searched in the table.
For my example it would be based on the "Chart column". I want to limit the table to only show the items that are based on chart "D" or Chart "S". Here is how I'm initializing the table.
if (!$.fn.DataTable.isDataTable( '#fundLookUptbl' ) ) {
fundTable = $('#fundLookUptbl').DataTable( {
data: funds,
columns: [
{ "mData": "chart" },
{ "mData": "fund" },
{ "mData": "orgDefault" },
{ "mData": "progDefault" }
]
} );
var filteredData = fundTable
.columns( [0, 1] )
.data()
.eq( 0 )
.filter( function ( value, index ) {
return value = 'D' ? true : false;
} );
}
This is obviously not working, and the filterData variable is a lousy attempt on trying to make it work. I'm having a hard time understanding the API's. So the question is , How can initialize the table to only show the items that are based on a given chart. I know that I can remove the items of the array but i don't want to do that since I would simple like to be able to switch between chart "D" and "S" but still continue to search through the other columns.
I believe that filtering the column would solve your problem.
table.column(0).search('Bruno').draw()
So you could just filter the column when the radio button selection change
Here is a fiddle example
I´m not sure to be understanding what you want to do but here are some options:
One way is selecting by default value example "s". You can use a dropdown is easier to handled .Then select with jQuery the dafault value "s" on that dropdown and add a function
$("#DropdownId").change(function () {
var chart=$("#DropdownId").val();
});
$.ajax({
url: "url")",//url to reload page with new value
type: "POST",
data: {chart:chart},
success: function (data) {
}
});
});
on this way the filter is on backend. If you want to do something on the row depending of a column value you shoud to add something like this
"fnRowCallback": function (nRow, mData, iDisplayIndex, iDisplayIndexFull) {
if (mData["chart"] =="s") {
return nRow;
}
},
Datatables: custom function inside of fnRowCallback.
Good luck
fundTable.order( [0, 'asc'] );
Try that or look at this particular page for reference:
https://datatables.net/reference/api/order%28%29
Basically orders in pair of columnIndex in either asc(ending) or desc(ending) order.