Pass value with a button - javascript

I have in my DB values in array.
"ExercisesData": [
{
"Id": "01",
"Reps": "10",
"StartDate": "2019-06-20",
"EndDate": "2019-06-21",
"Notes": "...."
},
{
"Id": "02",
"Reps": "1",
"Notes": "....."
},
{
"Id": "03",
"Reps": "150",
"Notes": "......"
}
]
I take these values and create a button for them. Like this:
checkAttività (){
//.....
}
render() {
const exercises = this.state.Exercises.map(exercise => {
return (
<View>
<Text style={{ fontSize: 15 }}>Id: {exercise.Id}</Text>
<Text style={{ fontSize: 15 }}>Reps: {exercise.Reps}</Text>
<Text style={{ fontSize: 15 }}>Note: {exercise.Notes}</Text>
<TouchableOpacity
style={[styleButton.button, styleButton.buttonOK]}
onPress={() => this.checkAttività(exercise.Id)}>
<Text style={styleButton.buttonTesto}>Choose</Text>
</TouchableOpacity>
</View>
In this way I create a button for every values in array. What I should do, is to create a button which allows me to pass the id value corresponding to the clicked key. In the sense:
Id: 01
Reps:
Notes: ...
Button1
Id: 02
Reps:
Notes: ...
Button2
If I click on the button1 I would pass the value of the Id (01). How can I do? Thank you.

Just add id parameter in checkAttività like:
checkAttività (id){
//.....
}
You already have used anonymous function, so it shoud do the trick:
onPress={() => this.checkAttività(exercise.Id)}
Also you should bind your event, eg in constructor:
this.checkAttività = this.checkAttività.bind(this)

You can do this. Just bind the event and you will be able to pass any params.
onPress={ this.someEvent.bind(this,exercise.Id)}
someEvent(id){
console.log("You will get the id: ",id);
}

Related

How to display state in FlatList ReactNative/React?

I have record state in my react native app.
state{
record:[] //some data inside, When i console my state it looks like this:
}
Console output of my record state:
Array [
Object {
"name": "abc",
"age": 23,
},
]
Array[
Object {
"name": "xyz",
"age": 27,
},
]
When i render it through FlatList it shows only first item of array that is name abc and age 23. While it should also load 2 array item in state, which is name xyz and age 27. below is the code for output of state.
displaydata(){
firebase.firestore()
.collection('users').where('age', '>=', 21)
.get()
.then(querySnapshot => {
querySnapshot.forEach(documentSnapshot => {
const urecords = [];
const udata = documentSnapshot.data();
urecords.push(udata);
this.setState({ record: [...urecords] })
});
});
}
}
render(){
return(
<View style={{ flex: 1 }}>
{this.state.record ? (
<>
<Text>Data from firebase firestore</Text>
<FlatList
style={{ flex: 1 }}
data={this.state.record}
keyExtractor={(key, index) => key + index}
renderItem={(itemData) => {
console.log(this.state.record); // it displays all data of state in console as i have consoled above
return <Text>{itemData.item.name}{itemData.item.age}</Text>; // it displays first array data(item) only, which is abc and 23
}
}
/>
</>
) : (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<ActivityIndicator size="large" color="black" />
</View>
)}
</View>
);
}
I want to load complete state on my screen.
It happens because you have 2 different arrays inside this.state.record.
Try to spread your data arrays inside state or combine them into 1 union array. Your this.state.record should look like this
state = {
records: [
{ name: 'xyz', age: '23', },
{ name: 'abc', age: '27', },
]
This will show you list with 2 objects
console.log('STATE RECORDS', this.state.records)
// console.log output
STATE RECORDS [
{ name: 'xyz', age: '23', },
{ name: 'abc', age: '27', },
]

How is React Native multiple data input?

My English is not very good, sorry for that. There is a structure that I want to make multiple data entries. I will add separate json lines for each input. But I can add once from the same line. But I want to create a separate json data for each input. I am sharing the sample code. It doesn't work that way because it constantly updates the previous data in.
var families = [];
for(let i = 0; i < formStep + 1; i++) {
families.push(
<View key={i}>
<View>
<Text style={{ marginBottom: 5 }}>T.C</Text>
<Input
placeholder='Lütfen T.C belirtin'
style={{ marginBottom: 10 }}
onChangeText={(input) => this.setState(prevState => ({
formData: [...prevState.formData, {tc: input}]
}))}
/>
</View>
<View>
<Text style={{ marginBottom: 5 }}>İsim</Text>
<Input
placeholder='Lütfen ad ve soyad belirtin'
style={{ marginBottom: 10 }}
/>
</View>
<View>
<Text style={{ marginBottom: 5 }}>Meslek</Text>
<Input
placeholder='Lütfen meslek belirtin'
style={{ marginBottom: 10 }}
/>
</View>
{(formStep > 0) ? <Divider style={{marginBottom: 15, marginTop: 10}}></Divider> : null}
</View>
)
}
working input onChangeText method;
Array [
Object {
"tc": "0",
},
]
Array [
Object {
"tc": "0",
},
Object {
"tc": "00",
},
]
Array [
Object {
"tc": "0",
},
Object {
"tc": "00",
},
Object {
"tc": "000",
},
]
But I want;
Array [
Object {
"tc": "000",
},
]
And then if there is more than one input;
Array [
Object {
"tc": "000",
},
Object {
"tc": "111",
},
Object {
"tc": "222",
},
]
I hope I could tell. Thanks for your help in advance.
If I understand what you want, you just need to overwrite the field you want to update this way:
onChangeText={(input) => this.setState(prevState => ({
formData: [...prevState.formData.tc, {tc: input}]
}))}
And for the other inputs, it would look something like this:
onChangeText={(input) => this.setState(prevState => ({
formData: [...prevState.formData.exemple, {exemple: input}]
}))}
You can also group input changes in one function:
updateText = (key, value) => {
// Merge the old key, or set it
this.setState(currentState => ({
formData: [
...currentState.formData,
[key]: value
]
}));
};
And you use it that way:
onChangeText={text => this.updateText("tc", text)}

How to setState on Object item within array

I want to update state of key heart in the array's objects when the heart icon pressed it changes to red so for this I'm using react native icons and i'm using heart and hearto to switch when click on it
here is the code:
state = {
localAdversiment: [
{
title: "Ecloninear 871",
image: require("../../assets/images/truck_image.png"),
year: "2015",
type: "Truck",
status: "new",
price: "$ 2000",
heart: "hearto"
}
Here it function which is called when heart icon pressed
handleFavourite = index => {
const { heart } = this.state.localAdversiment[index];
this.setState(
{
heart: "heart"
}
);
};
here is the heart icon code
<TouchableOpacity onPress={() => this.handleFavourite(index)}>
<Icon
name={item.heart}
type={"AntDesign"}
style={{ fontSize: 18 }}
/>
</TouchableOpacity>
kindly help me how to update heart as heart instead of hearto when clicked
You can do it easily by following approach
state = {
localAdversiment: [
{
id: 0,
title: "Ecloninear 871",
image: require("../../assets/images/truck_image.png"),
year: "2015",
type: "Truck",
status: "new",
price: "$ 2000",
heart: "hearto",
selected: false
}
}
now in onPress do this
handleFavourite = (item) => {
const { id } = item;
this.setState({
localAdvertisement: this.state.localAdvertisement.map((item) => {
if(item.id === id){
return {
...item,
selected: !item.selected
}
}
return item
})
})
};
Now render like this
<TouchableOpacity onPress={() => this.handleFavourite(item)}>
<Icon
name={item.selected ? "heart" : 'hearto'}
type={"AntDesign"}
style={{ fontSize: 18 }}
/>
</TouchableOpacity>
Hope it will help you
Edit this function as follows:
handleFavourite = index => {
let updatedlocalAdversimentStates = this.state.localAdversiment;
updatedlocalAdversimentStates[index].heart = "heart";
this.setState(
{
localAdversiment: updatedlocalAdversimentStates
}
);
};

PouchDB take array values

I have a problem with PouchDB with array values.
In my document on the DB I have:
"ExercisesData": [
{
"Id": "01",
"Reps": "10",
"StartDate": "2019-06-20",
"EndDate": "2019-06-21",
"Notes": ".........."
},
{
"Id": "02",
"Reps": "1",
"Notes": "........"
},
{
"Id": "03",
"Reps": "150",
"Notes": "........"
}
]
I need to print this values, and let choose one of these values (Id) at the user.
I've tried to take this values from the db in this way:
findUtente(cf) {
let params = {};
params = {
"Person.FiscalCode": cf
};
global.utente.db.localdb().find({
selector: {params},
})
.then(response => {
let utente = response.docs[0];
console.log(utente);
this.setState({ Id: utente.ExercisesData.Id })
console.log("utente.ExercisesData.Id: " + utente.ExercisesData.Id)
})
.catch(function(err) {
console.log(JSON.stringify(err));
});
}
render() {
console.log("this.state.Id: " + this.state.Id)
return(
<View>
<Text>{this.state.Id}</Text>
</View>
);
}
But this code go in the catch, give me back the error: {}
The problem should be that I'm trying to take the elements in wrong way. Maybe I should use the .Map param ?
How can I do to recover these value and print them in a page? Thank you.
I have solved in this way:
const exercises = this.state.Exercises.map(exercise => {
return (
<View>
<Text style={{ fontSize: 15 }}> {exercise.Id}</Text>
<Text style={{ fontSize: 15 }}> {exercise.Reps}</Text>
<Text style={{ fontSize: 15 }}> {exercise.Notes}</Text>

Props not being displayed in new route

I've been trying to learn React Native but it has been tougher than I thought. I can't create a simple "master-detail" app (and I couldn't find a good, simple tutorial explaining how to do it either).
I've managed to display a list of categories. After clicking one, it should display the category name + the list of items from this:
const data = [{
"category": "Fruits",
"items": [{
"name": "Apple",
"icon": "apple.png"
}, {
"name": "Orange",
"icon": "orange.png"
}]
}, {
"category": "Vegetables",
"items": [{
"name": "Lettuce",
"icon": "lettuce.png"
}, {
"name": "Mustard",
"icon": "mustard.png"
}]
}];
On my main class, I managed to display a list of categories:
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) =>
<Text onPress={this.onPressItem.bind(this, rowData.category)}>
{rowData.category}
</Text>}
/>
In my onPressItem I have the following:
onPressItem(category) {
this.props.navigator.push({
name: 'DetailView',
component: DetailView,
passProps: {
category
}
});
}
In my detail view, the category name is not being displayed:
class DetailView extends Component {
render() {
return (
<View style={ styles.container }>
<Text>Category: { this.props.category }</Text>
<TouchableHighlight onPress={ () => this.props.navigator.pop() }>
<Text>GO Back</Text>
</TouchableHighlight>
</View>
);
}
}
I'd really appreciate if someone can help me with this. It's probably something silly I'm doing wrong. Creating this simple thing can't be that hard. :/
Full code
I found a solution. I was making a mistake when rendering the view:
return React.createElement(
route.component,
{ navigator },
{...route.passProps}
);
The right way is:
return React.createElement(
route.component,
{ navigator, ...route.passProps }
);
Thanks to mehcode for helping me out.

Categories