Nothig shows with places.description == "Dermatologista" ?( - javascript

export default function Search({ navigation }) {
const [state, setState] = useState({
places: [
{
id: 1,
title: 'Clinica da pele',
description: 'Dermatologista',
latitude:-2.42206406,
longitude:-54.71947789,
},
{
id: 2 ,
title:'Unimed',
description:'Hospital',
latitude:-2.42501721,
longitude:-54.71146077,
},
{
id: 3,
title: 'Dra. Josimar',
description:'Dermatologista',
latitude: -2.4288346,
longitude:-54.7290553,
}
]
here I will take the itens to show
return(
</View>*/
<SafeAreaView>
<FlatList
styles = {styles.PlaceContainer}
showsVerticalScrollIndicator
data={state.places}
keyExtractor={item => item.id}
renderItem={({ item }) => {
here I tried to select the item witch the description is Dermatologista but it didnt shows anything
item.description == "Dermatologista" ? (
<View key={item.id} style={styles.place} >
<Text>{item.title}</Text>
<Text>{item.description}</Text>
</View>
):""
I cant show nothing when I try to select but when it was just a return it came back all the info
}
}
/>
</SafeAreaView>

You must map your data to get each value form the array
Use an array method like map you retrieve your data.
state.places.map((place) => {
console.log(place);
})
I'm just logging here but you can put this in your react component to print out each place.

Related

Can't pass the state props, says undefined

I have bee trying to pass the notes data to another component But I don't know why it says undefined.
export default App = () => {
const [notes, setNotes] = useState([
{ key: 1, value: "Hello there what up", title: "Some Title for this" },
{ key: 2, value: "I want to take notes", title: "another for this one" },
]);
return (
<View>
<FlatList
data={notes}
renderItem={({ note }) => (
<View>
<NoteItem note={note} />
</View>
)}
/>
</View>
);
};
export default NoteItem = ({ note }) => {
<Text>{note.title}</Text>
);
};
First of you assume that renderItem in Flatlist has a 'note' property inside it. It does not, it is called item. Also you pass notes but you try to deconstruct note? It should be like this:
export default App = () => {
const [notes, setNotes] = useState([
{ key: 1, value: "Hello there what up", title: "Some Title for this" },
{ key: 2, value: "I want to take notes", title: "another for this one" },
]);
return (
<View>
<FlatList
data={notes}
renderItem={({ item }) => (
<View>
<NoteItem note={item} />
</View>
)}
/>
</View>
);
};
This syntax - ({ note }) - means that the NoteItem component expects a prop named note to be set; however, you're setting the notes prop instead.
Try this:
<FlatList
data={notes}
renderItem={({ item, index }) => (
<View key={index}>
<NoteItem note={item} />
</View>
)}
/>

How to get the get data of Flatlist Item in reactNative

I am trying to get the data of a flat list when onPressed is called the onpressed is called as I am using an alert but the selected data is not getting called
import React from "react";
import {StyleSheet,Text,View,FlatList,TouchableWithoutFeedback,} from "react-native";
const App = () => {
return (
<View style={styles.container}>
<FlatList
data={[
{ key: "Devin" },
{ key: "Dan" },
{ key: "Jillian" },
{ key: "Jimmy" },
{ key: "Julie" },
]}
renderItem={({ item }) => (
<TouchableWithoutFeedback onPress={() => actionOnRow(item)}>
<View>
<Text style={styles.item}>Name: {item.key}</Text>
</View>
</TouchableWithoutFeedback>
)}
/>
</View>
);
};
const actionOnRow = (item) => {
const value = "Selected Item : "+ item;
alert(value);
};
export default App;
I have check the react documentation but i can't find anything on flatlist item OnPress, when i run this the alert displays the message "Selected : " but i am expecting "Selected : 'the item selected' ".
you are using alert . Alert does not accept two arguments.
Try using console.log or alert("Selected :" + item.key);
Answer in Full incase anyone else needs it
import React from "react";
import {StyleSheet,Text,View,FlatList,TouchableWithoutFeedback,} from "react-native";
const App = () => {
return (
<View style={styles.container}>
<FlatList
data={[
{ key: "Devin" },
{ key: "Dan" },
{ key: "Jillian" },
{ key: "Jimmy" },
{ key: "Julie" },
]}
renderItem={({ item }) => (
<TouchableWithoutFeedback onPress={() => selectStudent(item)}>
<View>
<Text style={styles.item}>Name: {item.key}</Text>
</View>
</TouchableWithoutFeedback>
)}
/>
</View>
);
};
const selectStudent = (item) => {
const value = "Selected Student : "+ item.key;
alert(value);
};
export default App;

React Native, accessing a single element from an array nested in state

how can I access a single element from an array nested in a state like this
state = {
modal: false,
post: [
{
key: "1",
title: "A Good Boi",
des: "He's a good boi and every one know it.",
image: require("../assets/dog.jpg"),
},
{
key: "2",
title: "John Cena",
des: "As you can see, You can't see me!",
image: require("../assets/cena.jpg"),
},
]
};
.....
<MyList.Provider
value={{
}}
>
<FlatList
data={this.state.post}
renderItem={({ item }) => (
<>
<TouchableOpacity
activeOpacity={0.7}
onPress={() => this.deleteItem(item)}
style={styles.Delete}
>
<MaterialCommunityIcons name="delete" color="red" size={30} />
</TouchableOpacity>
<TouchableOpacity
activeOpacity={0.7}
onPress={() => this.props.navigation.navigate("Edit", item)}
style={styles.Edit}
>
<MaterialCommunityIcons
name="playlist-edit"
color="green"
size={35}
/>
</TouchableOpacity>
<Card
title={item.title}
subTitle={item.des}
image={item.image}
onPress={() =>
this.props.navigation.navigate("Details", item)
}
/>
</>
)}
/>
</MyList.Provider>
how can I do this like this.state.post({title}) or some way else??
I need to use this values with context so I can share and change some particular data with between 2 screens. I know to pass data I need to use context or navigation.navigate("route name",item). But if I use navigation I won't able to edit it but how can I pass data in context value from array set, if I do this.state.post it will return whole list and if i do this.state.post[0].title it will return only title of that post. So how can i do this? Please help
You have to indicate the index of the object you’re trying to access in the array. For instance to access the first object in the array you can do this
this.state.post[0]
below is my solution which follows the logic i think you are trying to achieve. I have used a flatlist
Let me know if it helps
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity,
FlatList,
} from 'react-native';
export default class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
modal: false,
post: [
{
key: "1",
title: "A Good Boi",
des: "He's a good boi and every one know it.",
image: require("../assets/dog.jpg"),
},
{
key: "2",
title: "John Cena",
des: "As you can see, You can't see me!",
image: require("../assets/cena.jpg"),
},
]
};
}
handleEdit(item) {
const { post } = this.state;
const extractIndex = post.findIndex(e => e.key === item.key);
const newPost = post[extractIndex];
this.props.navigation.navigate('Edit', { newPost })
this.setState({ post });
}
handleDelete(item) {
const { post } = this.state;
const newPost = post.filter(e => e.key !== item.key);
this.setState({ post: newPost });
}
renderItem = ({ item }) => {
return (
<View>
<Text>
{item.title}
</Text>
<TouchableOpacity key={item.key} onPress={this.handleEdit.bind(this, item)}>
<Text>Edit</Text>
</TouchableOpacity>
<TouchableOpacity key={item.key} onPress={this.handleDelete.bind(this, item)}>
<Text>Delete</Text>
</TouchableOpacity>
</View>
);
}
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.post}
renderItem={this.renderItem}
keyExtractor={(item, index) => index.toString()}
extraData={this.state}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
Use .map() function
Ex-
var cat_data = categories_list.map(function (item) {
var cat_data = categories_list.map(function (item) {
return {
name: item.Name,
thumb_url: item.PictureModel.ImageUrl,
cat_id: item.Id.toString(),
};
});
this.setState({
data: cat_data,
});

map is not a function and picker problem in react native

I have problem with map my array about curriences.
so as u see there is a curriences array with strings. Im using Picker to choose some between them and I have function what is included to onValueChange prop in Picker, and then comes my problem with selecting an item from picker.
Firstly I can choose a whatever item from picker, but when I want to choose again I have just this choosed item before in the list:
then i choosed for example EUR. When I want to choose a item again I have just this:
Also when I change first picker item - it changes also in the second picker... don't know why.
also adding whole code here:
import React, {Component} from 'react';
import {View, Text, TextInput, Picker} from 'react-native';
class CurrencyCashScreen extends React.Component {
state = {
currencies: ['USD', 'AUD', 'SGD', 'PHP', 'EUR'],
base: 'PLN',
amount: '',
convertTo: 'EUR',
result: '',
date: '',
};
handleSelect = (itemValue, itemIndex) => {
this.setState(
{
...this.state,
currencies: [itemValue],
result: null,
},
this.calculate,
);
};
handleInput = text => {
this.setState(
{
...this.state,
amount: text,
result: null,
date: null,
},
this.calculate,
);
};
calculate = () => {
const amount = this.state.amount;
if (amount === isNaN) {
return;
} else {
fetch(`https://api.exchangeratesapi.io/latest?base=${this.state.base}`)
.then(res => res.json())
.then(data => {
const date = data.date;
const result = (data.rates[this.state.convertTo] * amount).toFixed(4);
this.setState({
...this.state,
result,
date,
});
});
}
};
handleSwap = e => {
const base = this.state.base;
const convertTo = this.state.convertTo;
e.preventDefault();
this.setState(
{
...this.state,
convertTo: base,
base: convertTo,
result: null,
},
this.calculate,
);
};
render() {
const {currencies, base, amount, convertTo, result} = this.state;
return (
<View>
<Text>
{amount} {base} is equevalent to
</Text>
<Text>
{amount === '' ? '0' : result === null ? 'Calculating...' : result}{' '}
{convertTo}
</Text>
<View>
<View>
<View>
<TextInput
keyboardType="numeric"
value={amount}
onChangeText={this.handleInput}
/>
<Picker
selectedValue={base}
value={base}
onValueChange={this.handleSelect}>
{currencies.map((currency, index) => (
<Picker.Item label={currency} value={currency}>
{currency}
</Picker.Item>
))}
</Picker>
</View>
<View>
<TextInput
editable={false}
value={
amount === ''
? '0'
: result === null
? 'Calculating...'
: result
}
/>
<Picker
selectedValue={convertTo}
value={convertTo}
onValueChange={this.handleSelect}>
{currencies.map(currency => (
<Picker.Item label={currency} value={currency}>
{currency}
</Picker.Item>
))}
</Picker>
</View>
</View>
<View>
<Text onClick={this.handleSwap}>CLICK ME</Text>
</View>
</View>
</View>
);
}
}
export default CurrencyCashScreen;
Please help.
See below example
you need two separate functions
import React, {Component} from 'react';
import {View, Text, TextInput, Picker} from 'react-native';
class CurrencyCashScreen extends Component {
state = {
currencies: ['USD', 'AUD', 'SGD', 'PHP', 'EUR'],
base: 'PLN',
convertTo: 'EUR',
amount: '',
result: '',
date: '',
};
handleSelectPicker1 = itemValue => {
this.setState(
{
base:itemValue
},
);
};
handleSelectPicker2 = itemValue => {
this.setState(
{
convertTo:itemValue
},
);
};
render() {
const {currencies, base, amount, convertTo, result,pickerValue1,pickerValue2} = this.state;
console.log('this.state',pickerValue1,pickerValue2)
return (
<View style={{flex:1}}>
<Picker
selectedValue={base}
//value={base}
onValueChange={this.handleSelectPicker1}>
{currencies.map((currency, index) => (
<Picker.Item label={currency} value={currency}/>
))}
</Picker>
<Picker
selectedValue={convertTo}
//value={convertTo}
onValueChange={
this.handleSelectPicker2
}>
{currencies.map(currency => (
<Picker.Item label={currency} value={currency}/>
))}
</Picker>
</View>
);
}
}
export default CurrencyCashScreen;
hope this will help you. Change this according to your requirement. Feel free for doubts.
Technically .map() requires an array to be executed on the variable.
I guess itemValue is not an array what you pass to handleSelect. That's why you have that error. I think if you modify the code to handle currencies as an array then it should work.
handleSelect = itemValue => {
this.setState(
{
...this.state,
currencies: [itemValue],
result: null,
},
this.calculate,
);
};
I hope that helps!
More than likely currencies is not an array. Here is what I recommended:
Check to make sure that you've properly destructured your state earlier in the render function like const { currencies } = state; Any typos here may cause the error.
Make sure currencies is set with a sane default. If currencies is undefined when your component first mounts, you will get this error.
Use console.log, or a debugger to view the value of currencies. If it is not an array (including undefined) when you call the currencies.map method, then you will get this error.

How to display correctly several Flatlist with a map function?

I have an issue that I don't quite understand.
I would like to display messages contained in an array using several flatlists. Then I will have to group them by date.
The messages actually correspond to a series of questions and answers from a chat where each message is recorded in an offline database (PouchDB is used). So I would like to display in an interface the questions that the user has answered, in short, I want to view the logs.
Here is the code:
const screen = Dimensions.get('screen');
const styles = StyleSheet.create({
logsView: {
backgroundColor: '#dddddd',
paddingLeft: 15,
paddingRight: 2,
height: '100%',
},
dateContainer: {
width: '75%',
padding: 1,
marginTop: 5,
},
dateContent: {
textAlign: 'center',
},
});
export default class ComponentPlanDetailsScreen
extends ComeoMeAbstractScreen<PropsType, StateType> {
static navigationOptions = {
title: µte('MyPlans'),
headerRight: (<View />),
};
constructor(props: PropsType) {
super(props);
this.IfeelMessagesBusiness = new IfeelMessagesBusiness();
this.state = {
currentDate: new Date(),
markedDate: moment(new Date()).format('YYYY-MM-DD'),
messages: [],
};
}
componentDidMount = () => {
// Get all messages from chat history
this.IfeelMessagesBusiness.getAllIfeelMessages().then((result: Object) => {
this.setState({ messages: result });
});
};
// Render each item of Flatlist
renderLogItem = ({ item }: Object) => {
console.log(`je passe renderlogitem ${JSON.stringify(item)}`);
return <LogItem message={item} />;
}
// Key for data in FlatList component
keyExtractor = (item: Object, index: number): string => index.toString();
render() {
const test = [
{
stringValue: 'Did you take some drugs ?',
isImage: false,
isQuestion: true,
questionNumber: 6,
author: {
id: 1,
avatar: 'http://image.noelshack.com/fichiers/2016/47/1480031586-1474755093-risitas721.png',
username: 'Dr Risitas',
},
loggedDateTime: '1552033946989',
},
];
const today = this.state.currentDate;
const day = moment(today).format('x');
return (
<View>
<Carousel
animate={false}
indicatorSize={10}
height={screen.height * 0.7
}
>
<View>
<ScrollView
style={styles.logsView}
>
<View>
{this.state.messages.map((ItemListByDate: Object): Array<Object> => {
console.log(`je passe array ${JSON.stringify([ItemListByDate])}`);
return (
<View key={ItemListByDate.loggedDateTime.toString()}>
<View style={styles.dateContainer}>
{ (parseInt(ItemListByDate.loggedDateTime, 10) + 172800000) <= parseInt(day.toString(), 10) ?
<Text style={styles.dateContent}>{moment(parseInt(ItemListByDate.loggedDateTime, 10)).format('DD-MM-YYYY')}</Text>
:
<Text style={styles.dateContent}>{moment(parseInt(ItemListByDate.loggedDateTime, 10)).fromNow()}</Text>
}
</View>
<View>
<FlatList
data={[ItemListByDate]}
renderItem={this.renderLogItem}
keyExtractor={this.keyExtractor}
ref={(ref: any) => { this.flatList = ref; }}
onContentSizeChange={(): any => this.flatList.scrollToEnd({ animated: true })}
onLayout={(): any => this.flatList.scrollToEnd({ animated: true })}
/>
</View>
</View>);
})
}
</View>
</ScrollView>
</View>
</Carousel>
</View>
);
}
}
The problem I don't understand is that the renderLogItem function to call the LogItem component is never called while the ItemListByDate array is displayed in the logs. No messages are displayed, I just have the grey background of the ScrollView component.
On the other hand, if I use the test array instead of this.state.messages with the map function, the message is displayed correctly in the interface and renderLogItem is called correctly.
I understand that when my component is called for the first time, the state is empty and the switch to the componentDidMount function will in my case trigger the update of the state and cause a re-render. This also causes the map function to call up and normally displays each message
Maybe it is due to a display problem, where the messages would be hidden because the initial state of the messages is empty ?
Thank you in advance for your help !
My first thought is that it has to do with the fact that this.IfeelMessagesBusiness.getAllIfeelMessages() is asynchronous. So the first time the render method is called, it tries to map òver undefined and it never updates.
Could you try doing a flatlist of Flatlist maybe ?

Categories

Resources