TextInput field not fetching value inside Map function react-native - react-native

i want to fetch 'DeliveredQuantity' in Textinput Field, do anyone know solution for this
const [arrayList, setArraylist]= [
{id:0, ExpectedQuantity:10, DeliveredQuantity:7},
{id:1, ExpectedQuantity:19, DeliveredQuantity:9},
{id:2, ExpectedQuantity:11, DeliveredQuantity:11},
{id:3, ExpectedQuantity:45, DeliveredQuantity:30},
]
arrayList.map((items,index)=>{
return
<TextInput value={items.DeliveredQuantity} />
})

Store the array in a state and use it like this
const [arrayList, setArraylist] = React.useState([
{ id: 0, ExpectedQuantity: 10, DeliveredQuantity: 7 },
{ id: 1, ExpectedQuantity: 19, DeliveredQuantity: 9 },
{ id: 2, ExpectedQuantity: 11, DeliveredQuantity: 11 },
{ id: 3, ExpectedQuantity: 45, DeliveredQuantity: 30 },
]);
return (
<View style={styles.container}>
{arrayList.map((items, index) => (
<TextInput value={items.DeliveredQuantity} />
))}
</View>
);
Working Example

Related

Flatlist doesn't render an array of Objects

Hello everybody i'm trying to render a list of objects to rapresent some letters, taken from a custom keyboard. my flatlist look like this:
<FlatList
horizontal={true}
data = {keyList}
renderItem = {({item}) =>
<View style={styles.singleBlock}>
<Text style={styles.textBlock}>{item.letter}</Text>
</View>
}
keyExtractor = {myKey}
/>
the data is taken from my state:
const [keyList, setKeyList] = useState([
{
'letter': "",
'state': "nonIndovinato",
'id': 1
},
{
'letter': "",
'state': "Indovinato",
'id': 2
},
{
'letter': "",
'state': "Indovinato",
'id': 3
},
{
'letter': "",
'state': "Indovinato",
'id': 4
},
{
'letter': "",
'state': "Indovinato",
'id': 5
}
]);
and updated by update function:
const updateData = (key) => {
const index = keyList.findIndex(item => item.id === key.id);
if(index === -1) return;
const item = keyList[index];
const updatedItem = {...item, letter: key.letter};
const updatedArray = keyList;
updatedArray[index] = updatedItem;
setKeyList(updatedArray);
};
the key value is something as follow:
{
'letter': 'A',
'id': 1
}
the data i see with console.log is right, for example if i press T it look like this:
{letter: 'T', state: 'nonIndovinato', id: 1},
{letter: '', state: 'Indovinato', id: 2},
{letter: '', state: 'Indovinato', id: 3},
{letter: '', state: 'Indovinato', id: 4},
{letter: '', state: 'Indovinato', id: 5}
the application look like this: https://i.stack.imgur.com/JhQiq.jpg
the upper part is the structure where it should be displayed the data, the lower is the expected result with mockup data.
if you need the style:
singleBlock: {
backgroundColor: 'grey',
width: width/6,
justifyContent: 'center',
alignItems: 'center',
margin: 1,
marginTop: '5%',
marginBottom: '5%',
marginRight: 2,
borderRadius: 1
},
textBlock: {
color: 'white',
fontSize: width/10,
fontWeight: 'bold'
}
Thanks to anyone who can help :)
The way you are updating your state is not correct. Try the following.
const updateData = (key) => {
const index = keyList.findIndex(item => item.id === key.id);
if(index === -1) return;
const item = keyList[index];
const updatedItem = {...item, letter: key.letter};
let updatedArray = [...keyList];
updatedArray[index] = updatedItem;
setKeyList(updatedArray);
};

Insert Data to State in React Native

I have a list data and a input type for add data, so I make state for save data and rendering it. I want when I type text in TextInput then I enter so data will added. but for this issue, screen must to be refresh for data added.
const [dataSubjects, setDataSubject] = useState([
{
id: "PPKN",
name: "Pendidikan Pancasila dan Kewarganegaraan (PPKn)",
},
{
id: "BI",
name: "Bahasa Indonesia (BI)",
},
{
id: "MAT",
name: "Matematika (MAT)",
},
{
id: "IPA",
name: "Ilmu Pengetahuan Alam (IPA)",
},
{
id: "IPS",
name: "Ilmu Pengetahuan Sosial (IPS)",
},
{
id: "SBDP",
name: "Seni Budaya dan Prakarya (SBdP)",
},
{
id: "PJOK",
name: "Pendidikan Jasmani, Olahraga, dan Kesehatan (PJOK)",
},
])
const HandleSubmit = (name) => {
setText("")
setDataSubject((prevSubject) => {
return [{ name, id: Math.random().toString() }, ...prevSubject]
})
}
This is a code for state data and function add data
<TextInput
visible={inputSubject}
mode="outlined"
placeholder="Type other subject…"
underlineColor="transparent"
value={text}
style={{
backgroundColor: theme.colors.surface,
fontSize: 14,
borderRadius: 4,
flex: 1,
}}
onChangeText={handleChangeText}
onSubmitEditing={() => HandleSubmit(text)}
/>
this is a TextInput code
Are you trying to add whatever you type in <TextInput/> as a new item in dataSubjects? If you are you can add an item to an array by using either of the two:
Array.prototype.unshift() to addd an item at the start of the array
Array.prototype.push() to add an item at the end of the array
Specifically, you can try something like this:
const HandleSubmit = (name) => {
setText("")
setDataSubject(dataSubjects.unshift({name: name, id: Math.random().toString()})
}

Set Selected items in react native multi select

I want to select the selected items which i already select & save at backend after that if i get response then set already selected those items which i have set in react native multi select
here is my code for react native multiselect
//Example Multiple select / Dropdown / Picker in React Native
import React, { Component } from "react";
//Import React
import { View, Text, Picker, StyleSheet, SafeAreaView } from "react-native";
//Import basic react native components
import MultiSelect from "react-native-multiple-select";
//Import MultiSelect library
//Dummy Data for the MutiSelect
this.items = [
{ id: "1", name: "America" },
{ id: "2", name: "Argentina" },
{ id: "3", name: "Armenia" },
{ id: "4", name: "Australia" },
{ id: "5", name: "Austria" },
{ id: "6", name: "Azerbaijan" },
{ id: "7", name: "Argentina" },
{ id: "8", name: "Belarus" },
{ id: "9", name: "Belgium" },
{ id: "10", name: "Brazil" }
];
export default class App extends Component {
state = {
//We will store selected item in this
selectedItems: [
{ id: "1", name: "America" },
{ id: "2", name: "Argentina" },
{ id: "3", name: "Armenia" },
{ id: "4", name: "Australia" }
]
};
onSelectedItemsChange = selectedItems => {
this.setState({ selectedItems });
//Set Selected Items
};
render() {
const { selectedItems } = this.state;
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={{ flex: 1, padding: 30 }}>
<MultiSelect
hideTags
items={items}
uniqueKey="id"
ref={component => {
this.multiSelect = component;
}}
onSelectedItemsChange={this.onSelectedItemsChange}
selectedItems={selectedItems}
selectText="Pick Items"
searchInputPlaceholderText="Search Items..."
onChangeInput={text => console.log(text)}
tagRemoveIconColor="#CCC"
tagBorderColor="#CCC"
tagTextColor="#CCC"
selectedItemTextColor="#CCC"
selectedItemIconColor="#CCC"
itemTextColor="#000"
displayKey="name"
searchInputStyle={{ color: "#CCC" }}
submitButtonColor="#48d22b"
submitButtonText="Submit"
/>
<View>
{this.multiSelect &&
this.multiSelect.getSelectedItemsExt(selectedItems)}
</View>
</View>
</SafeAreaView>
);
}
}
Got it.
this.state={
selectedData: "158" // list of id here(without space, that is your response of api)
};
<MultiSelect
.....
.....
selectedItems={selectedData}
/>
<View>
{this.multiselect ? this.multiSelect.getSelectedItemsExt(selectedData): null}
</View>
I had this same issue and I figured out how to preset selections by using parts of the accepted answer.
I learned that selectedItems is a list of whatever is set as the uniqueKey in the MultipleSelect props.
For example, if you put the uniqueKey as a numbered id of each list member and you wanted the second member set as selected, you would have selectedItems = {[ "2" ]}
I hope this makes sense.

React native component does not react to mobx observable data change

so I started to build a new app with react native and mobx.
I have a flat list component that gets his state data from the mobx store list. and when i'm adding new item to the mobx list, it won't re render the flat list view.
here is my code:
List Component:
#inject('TravelStore')
#observer
class TripsList extends Component {
constructor(props) {
super(props);
this.state = {
trips_list: props.TravelStore.trips_list
}
};
// set the navigation bar options
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return {
title: 'Your Trips',
headerRight: (
<Button transparent primary onPress={ params.addNewTrip }>
<Icon name='ios-add' />
</Button>
)
};
};
// connect between component functions to header
componentDidMount() {
this.props.navigation.setParams({
addNewTrip: this._addNewTrip.bind(this),
});
}
_addNewTrip() {
this.props.TravelStore.addNewTrip('bla')
}
_renderListItem({ item }) {
return (
<TripsListItem details={item} navigation={this.props.navigation}/>
);
};
render() {
return (
<Container>
<FlatList
data = {this.state.trips_list}
renderItem = {this._renderListItem.bind(this)}
keyExtractor={(item, index) => index}
/>
</Container>
);
};
}
mobx store:
class ObservableTravelListStore {
#observable trips_list = [
{
name: 'to denver',
trip_cost: 400,
buying_list: [
{ name: 'pizza', price: 10 },
{ name: 'burger', price: 40 },
{ name: 'ipad', price: 44 },
{ name: 'bus', price: 45 },
]
},
{
name: 'to yafo',
trip_cost: 30,
buying_list: [
{ name: 'na na na', price: 10 },
{ name: 'burger', price: 40 },
]
},
{
name: 'to tel aviv',
trip_cost: 50,
buying_list: [
{ name: 'na na na', price: 10 },
{ name: 'no no no', price: 40 },
]
},
]
#action addNewTrip (trip_data) {
this.trips_list.push({
name: 'newTrip',
trip_cost: 6060,
buying_list: [
{ name: 'na na na', price: 10 },
{ name: 'burger', price: 40 },
]
})
console.log(this.trips_list[3])
}
}
const TravelStore = new ObservableTravelListStore()
export default TravelStore
any idea why the TripsList component won't rerender when addNewTrip function is called?
the problem is that you are not listening to the real observable but to a copy of it, you save in state in the constructor.
<FlatList
data = {this.state.trips_list}//change this
renderItem = {this._renderListItem.bind(this)}
keyExtractor={(item, index) => index}
/>
<FlatList
data = {this.props.TravelStore.trips_list}//change to this
renderItem = {this._renderListItem.bind(this)}
keyExtractor={(item, index) => index}
/>
the render function is like autobind of mobx and react to changes in the observable if it's a render function of an observer
if you want to react to inner changes in the items of the list,
you should add an observable scheme and this should do the trick,
something like this:
class TripModel {
#observable name = ''
#observable trip_cost = 0
#observable buying_list = []
constructor(name, cost, buy_list){
this.name = name
this.trip_cost = cost
this.buying_list = buy_list
}
/* class functions*/
}
class ObservableTravelListStore {
#observable trips_list = [
new Trip(
'to denver',
400,
[
{ name: 'pizza', price: 10 },
{ name: 'burger', price: 40 },
{ name: 'ipad', price: 44 },
{ name: 'bus', price: 45 },
]
),
new Trip(
'to yafo',
30,
[
{ name: 'na na na', price: 10 },
{ name: 'burger', price: 40 },
]
),
new Trip(
'to tel aviv',
50,
[
{ name: 'na na na', price: 10 },
{ name: 'burger', price: 40 },
]
)
]
#action addNewTrip (trip_data) {
this.trips_list.push(new Trip(
'newTrip',
6060,
[
{ name: 'na na na', price: 10 },
{ name: 'burger', price: 40 },
]
))
}
}
const TravelStore = new ObservableTravelListStore()
export default TravelStore
this is just better planning for reactive apps, so on change to inner content of the items in the list you will react to this change
hope that helps
Its an old post, but I also got stuck with something similar recently. Adding extraData in Flatlist prop list helped me.
<FlatList
data = {this.props.TravelStore.trips_list}
renderItem = {this._renderListItem.bind(this)}
keyExtractor={(item, index) => index}
extraData={this.props.TravelStore.trips_list.length} // list re-renders whenever the array length changes
/>
And as #Omri pointed out, you shouldn't be storing the observable in the Component state but make changes to it directly.

In react native how to append fetch response array object in to render function?

I Need to Display Below the Array Data into Render Function :
I would Know how to loop the data and display it in Render.
[{
profileid: 1,
enabled: 1,
attachment: '',
id: 233,
topicid: 47,
tstamp: 'January, 21 2016 15:06:31 +1100',
body: 'to check orders'
}, {
profileid: 2,
enabled: 1,
attachment: '',
id: 233,
topicid: 47,
tstamp: 'January, 21 2016 15:06:31 +1100',
body: 'to check orders'
} ]
I hope I help you
class Parent extends React.Component{
constructor(props){
super(props);
this.state = {
gists : []
}
}
componentDidMount() {
fetch('http://rest.......')
.then(response => response.json())
.then(gists => this.setState({ gists }))
}
render(){
return (
<ul>
{this.state.gists.map(gist => (
<li key={gist.countryId}>{gist.name}</li>
))}
</ul>
)
}
}
Parent.propTypes = {
data: React.PropTypes.array
}
Here is an example.
import React from 'react'
import { View, Text } from 'react-native'
...
const data = [{
profileid: 1,
enabled: 1,
attachment: '',
id: 233,
topicid: 47,
tstamp: 'January, 21 2016 15:06:31 +1100',
body: 'to check orders'
}, {
profileid: 2,
enabled: 1,
attachment: '',
id: 233,
topicid: 47,
tstamp: 'January, 21 2016 15:06:31 +1100',
body: 'to check orders'
} ]
...
render() {
return (
<View>
{data.map((dataItem) =>
<View key={dataItem.profileid}>
<Text>{dataItem.profileId}</Text>
<Text>{dataItem.enabled}</Text>
<Text>{dataItem.attachment}</Text>
<Text>{dataItem.id}</Text>
<Text>{dataItem.topicid}</Text>
<Text>{dataItem.tstamp}</Text>
<Text>{dataItem.body}</Text>
</View>
)}
</View>
)
}