Sort array by value and alphabet React Native - javascript

I get an array from firebase, it is now sorted alphabetically. If an object contains 'routes' then it will get the text 'Bekijk' button otherwise the text 'coming soon' button, what I would like is that the objects with the name 'Bekijk' are displayed first and then the other objects alphabetically order, does anyone know if that is possible?
This is my code:
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Image, ImageBackground, StatusBar, ScrollView, Dimensions, TouchableOpacity} from 'react-native';
import { Header, Icon,Button,Rating, AirbnbRating } from 'react-native-elements';
import firebase from 'react-native-firebase';
class routeScreen extends Component {
constructor(props){
super(props);
this.state = {
goverments: [],
}
}
getGovermentData = () => {
let ref = firebase.database().ref('Goverments');
ref.on('value' , snapshot =>{
var state = snapshot.val();
this.setState({
goverments: state,
})
console.log(state);
})
}
componentWillMount(){
this.getGovermentData();
}
render() {
const width = {
width: (Dimensions.get('window').width / 2),
};
return (
<ScrollView>
{
this.state.goverments.sort(function(a, b) {
if(a.name.toLowerCase() < b.name.toLowerCase()) return -1;
if(a.name.toLowerCase() > b.name.toLowerCase()) return 1;
return 0;
}).map((item, i) => (
<View style={[styles.cards, { backgroundColor: (i % 2 == 0) ? '#D1A96E' : '#A58657' }]}>
<View style={styles.leftcolum}>
<Text style={styles.title}>{item.name}</Text>
<Text style={styles.undertitle}>4km - 5km - 7km</Text>
<Image source={require('./assets/images/stars.png')} style={styles.stars}/>
<Button buttonStyle={{
backgroundColor: item.routes ? "#3F494B" : "#018786",
marginTop: 40,
borderRadius: 50,
}} title={item.routes ? "Bekijk" : "Coming soon"}
onPress={() => item.routes ? this.props.navigation.navigate('Location', {govermentData: item}) : '#'}
/>
</View>
<View style={styles.rightcolum}>
<Image source={{uri: item.logoUrl}} style={{width: 150, height: 68}}/>
</View>
</View>
))
}
</ScrollView>
);
}
}
const styles = StyleSheet.create({
cards:{
backgroundColor: '#D1A96E',
borderRadius: 10,
marginTop: 20,
marginRight: 10,
marginLeft: 10,
paddingLeft: 20,
paddingRight: 20,
paddingTop: 20,
paddingBottom: 20,
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
alignItems: 'flex-start'
},
stars:{
marginTop: 10,
},
leftcolum:{
width: '50%',
},
rightcolum:{
width: '50%',
paddingTop:30,
paddingLeft:10,
},
title:{
fontSize: 17,
color: '#fff',
marginTop: 5,
fontWeight: '800',
},
undertitle:{
fontSize: 12,
color: '#fff',
fontWeight: '200',
},
button:{
backgroundColor: '#3F494B',
borderRadius: 22,
marginTop: 20,
},
valkenburg:{
backgroundColor: '#A58657',
},
gulpen:{
backgroundColor: '#EBC285',
},
logoValkenburg:{
width: '50%',
paddingTop:10,
paddingLeft:10,
},
logoGulpen:{
width: '50%',
paddingTop:30,
paddingLeft:10,
}
});
export default routeScreen;
Structure of array:
what I would like:
now the array is shown in alphabetical order, that is good, I would only like to show object 1 of Goverments at the top because it contains the value routes, with the others the value routes being empty. so if it is filled, it must show it at the top

const Goverments = [
{
name: 'Valkenburg',
},
{
name: 'Eijsden-Margeaten',
},
{
name: 'Gulpen',
routes: [],
},
];
const SortedGoverments = Goverments.sort(function(a, b) {
if(a.routes) return -1; // new check
if(b.routes) return 1; // new check
if(a.name.toLowerCase() < b.name.toLowerCase()) return -1;
if(a.name.toLowerCase() > b.name.toLowerCase()) return 1;
return 0;
});
console.log("Goverments : ", Goverments);
console.log("SortedGoverments : ", SortedGoverments);

Related

Getting error in snack expo while using 'expo-image-picker' : 'NoSuchKeyThe specified key does not exist'

I am creating a react native app on snack expo.
The app allows the user to select image from device on screen one (PhotoSelection.js) and shows the image to screen 2 (FrameSelection.js). Upon selecting an image from device, I am receiving this error:
NoSuchKeyThe specified key does not exist.v2/46/FrameSelectionM0EK0RMAJZ9JH00KGQ3jUVOsp2fXZp3ZWPaMeUjM57WUcEEUGHNvluc/kOn1FcOfRMnlOquUUUZVYGaB/d2cQQNh0Ko=
Screen 1 (PhotoSelection.js):
import React from 'react';
import { StatusBar } from 'expo-status-bar';
import { Text, View, StyleSheet, Image, TouchableOpacity, Button} from 'react-native';
import MyCustomFont from '../assets/Poppins-Bold.ttf';
import { useNavigation } from '#react-navigation/native';
import * as ImagePicker from 'expo-image-picker';
import { Constants } from 'expo-constants';
export const PhotoSelection =() =>{
const handleSelectImage = async () => {
try {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
});
if (!result.cancelled) {
navigation.navigate('FrameSelection', { image: result.uri });
}
} catch (error) {
console.log(error);
}
};
return (
<View style ={styles.container}>
<View>
<Image
style = {styles.img1}
source={require('../assets/image 1.png')}
/>
</View>
<View>
<Image
style = {styles.img2}
source ={require('../assets/Group 546020456.png')}
/>
</View>
<Text style={styles.text}>
Frame your special photos & share it with your friends
</Text>
<TouchableOpacity style ={styles.touchbutton}
onPress={handleSelectImage}
>
SELECT PHOTO
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex:1,
backgroundColor: '#603FC0',
justifyContent: 'center',
alignItems:'center',
width:'100%'
},
img1:{
width:360,
resizeMode:'cover'
},
img2:{
"width":220,
marginTop:50
},
text: {
"width": 200,
"fontFamily": 'MyCustomFont',
"fontStyle": "normal",
"fontWeight": "500",
"fontSize": 16,
"lineHeight": 24,
"textAlign": "center",
},
touchbutton:{
marginTop: 30,
paddingLeft:40,
paddingRight:40,
borderRadius:8,
paddingTop:16,
paddingBottom:16,
alignSelf:'center',
backgroundColor:'white',
fontFamily: 'MyCustomFont',
fontStyle: 'normal',
fontWeight: 700,
fontSize: 16,
},
});
Screen 2 (FrameSelection.js):
import React, {useState} from 'react';
import { Text, View, StyleSheet, Image, TouchableOpacity} from 'react-native';
import {PhotoSelection} from './PhotoSelection';
import { Constants } from 'expo-constants';
export const FrameSelection =({route}) =>{
const frames =
[
{ id: 1, small: require('../assets/image 4.png'), large: require('../assets/image 4.png') },
{ id: 2, small: require('../assets/image 4.png'), large: require('../assets/image 4.png') },
{ id: 3, small: require('../assets/image 4.png'), large: require('../assets/image 4.png') },
];
const [selectedFrame, setSelectedFrame] = useState(frames[0]);
const handleImagePress = (frame) => {
setSelectedFrame(frame);
};
return (
<View style={{ flex: 1 }}>
<View style={{ flex: 1 }}>
{route.params.image ? (
<Image source={{ uri: route.params.image }} style={{position: 'absolute', padding:0, top: 0, left: 0, width: '100%', height: '100%', resizeMode: 'contain', backgroundColor: 'white', zIndex: 1} } />
) : (
<Text>No image selected</Text>
)}
<Image
source={selectedFrame.large}
style={{flex:1,position: 'absolute', resizeMode: 'contain', top: 0, left: 0, width: '100%', height: '100%', zIndex: 2}}
resizeMode="contain" />
</View>
<View style={{ flexDirection: 'row', height: 100 }}>
{frames.map((frame) => (
<TouchableOpacity onPress={() => handleImagePress(frame)}>
<Image source={frame.small} style={{ width: 60, height: 60, margin: 10 }} resizeMode="contain" />
</TouchableOpacity>
))}
</View>
</View>
);
};
I Tried checking if the selected image's uri is being passed correctly.

Unable to update state in react native component using onChangeText

I have been trying to update the email and password value on submitting the form
so that I can pass them in my login API parameters. But I have tried almost everything, the value of this.state won't just update. Every time I try to print the value in console log e.g: cosole.log(this.state.email), it prints empty string i.e the default value set previously.
Here is my code below:
login.js
import React, { Component } from 'react';
import { ThemeProvider, Button } from 'react-native-elements';
import BliszFloatingLabel from './BliszFloatingLabel'
import {
StyleSheet,
Text,
View,
Image,
TextInput,
Animated,
ImageBackground,
Linking
} from 'react-native';
const domain = 'http://1xx.xxx.xx.xxx:8000';
class Login extends Component {
state = {
email: '',
password: '',
}
LoginAPI = (e,p) => {
console.log(e, "####")
}
handleEmail = (text) => {
this.setState({ email: text })
}
handlePassword = (text) => {
this.setState({ password: text })
}
goToSignUpScreen=() =>{
this.props.navigation.navigate('SignUpScreen');
};
goToForgotPasswordScreen=() =>{
this.props.navigation.navigate('ForgotPasswordScreen');
};
render() {
return (
<View style={styles.container} >
<ImageBackground source={require('../bgrndlogin.jpeg')} style={styles.image} >
<View style={styles.heading}>
<Image style={styles.logo} source={require('../loginlogo.png')} />
<Text style={styles.logoText}>Login</Text>
<Text style={styles.logodesc}>Please Login to continue --></Text>
</View>
<View style={styles.form_container}>
<BliszFloatingLabel
label="Email Id"
value={this.state.email}
onChangeText = {this.handleEmail}
onBlur={this.handleBluremail}
/>
<BliszFloatingLabel
label="Password"
value={this.state.password}
onChangeText = {this.handlePassword}
onBlur={this.handleBlurpwd}
secureTextEntry={true}
/>
<ThemeProvider theme={theme}>
<Button buttonStyle={{
opacity: 0.6,
backgroundColor: '#CC2C24',
borderColor: 'white',
borderWidth: 1,
width: 200,
height: 50,
marginTop: 30,
marginLeft: '20%',
alignItems: 'center',
justifyContent: "center"
}}
title="Login"
type="outline"
onPress = {
() => this.LoginAPI(this.state.email, this.state.password)
}
/>
</ThemeProvider>
<Text style={{
marginTop: 70,
color: '#CC2C24',
fontSize: 16,
fontWeight: "bold"
}}
onPress={
this.goToForgotPasswordScreen
}>
Forgot Password?
</Text>
<Text style={{
marginTop: 20,
color: '#CC2C24',
fontSize: 16,
fontWeight: "bold"
}}
onPress={
this.goToSignUpScreen
}>
Don't have an Account?
</Text>
</View>
</ImageBackground>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
logo: {
width: 115,
height: 50,
},
logoText: {
color: 'white',
fontSize: 36,
fontWeight: "bold"
},
logodesc: {
color: '#CC2C24',
fontSize: 18,
fontWeight: "bold"
},
heading: {
flex: 3,
marginLeft:20,
marginTop:30
},
form_container: {
flex: 7,
marginLeft:20,
marginTop:30,
marginRight: 20,
},
image: {
flex: 1,
resizeMode: "cover",
justifyContent: "center"
},
});
const theme = {
Button: {
titleStyle: {
color: 'white',
fontWeight: "bold",
fontSize: 18
},
},
};
export default Login;
I have created a common form as below which I inherit everywhere :
BliszFloatingLabel.js
import React, { Component } from 'react';
import {
Text,
View,
TextInput,
Animated,
} from 'react-native';
class BliszFloatingLabel extends Component {
state = {
entry: '',
isFocused: false,
};
UNSAFE_componentWillMount() {
this._animatedIsFocused = new Animated.Value(0);
}
handleInputChange = (inputName, inputValue) => {
this.setState(state => ({
...state,
[inputName]: inputValue // <-- Put square brackets
}))
}
handleFocus = () => this.setState({ isFocused: true })
handleBlur = () => this.setState({ isFocused: true?this.state.entry!='' :true})
handleValueChange = (entry) => this.setState({ entry });
componentDidUpdate() {
Animated.timing(this._animatedIsFocused, {
toValue: this.state.isFocused ? 1 : 0,
duration: 200,
useNativeDriver: true,
}).start();
}
render() {
// console.log(this.state.entry)
const { label, ...props } = this.props;
const { isFocused } = this.state;
const labelStyle = {
position: 'absolute',
left: 0,
top: !isFocused ? 40 : 0,
fontSize: !isFocused ? 16 : 12,
color: 'white',
};
return (
<View style={{ paddingTop: 20,paddingBottom:20 }}>
<Text style={labelStyle}>
{label}
</Text>
<TextInput
{...props}
style={{
height: 50, fontSize: 16, color: 'white', borderBottomWidth: 1, borderBottomColor: "white"
}}
value={this.state.entry}
onChangeText={this.handleValueChange}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
blurOnSubmit
/>
</View>
)
}
}
export default BliszFloatingLabel;
Instead of passing onChangeText like this onChangeText={this.handleValueChange} pass in a callback in BliszFloatingLabel and also in Login component.
onChangeText={(text)=>this.handleValueChange(text)}
Snack with the fixture.
https://snack.expo.io/#waheed25/d16fb3

How to set dynamic height for each row with react-native-swipe-list-view?

Description
I am working on a react-native project using expo SDK36.
I want to do a swipe left/right list view. I use react-native-swipe-list-view to achieve it.
So far everything worked perfectly, the default example uses a fixed height: 50 per row, while I want to set the height of each row dynamically.
Every attempt where a failure, note that I already use <SwipeListView recalculateHiddenLayout={true} />
This is bad for the UX, since the default line is having a small height: 50, it is nearly impossible to drag the line on iOS and android properly.
Reproduction
Snack: https://snack.expo.io/#kopax/react-native-swipe-list-view-408
import React from 'react';
import { Dimensions, Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import SwipeListView from './components/SwipeListView';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.paragraph}>
Change code in the editor and watch it change on your phone! Save to get a shareable url.
</Text>
<Card>
<SwipeListView
dimensions={Dimensions.get('window')}
listViewData={Array(20).fill('').map((d, i) => ({
...d,
title: `Item ${i}`,
description: `This is a very long description for item number #${i},
it should be so long that you cannot see all the content,
the issue is about fixing the dynamic height for each row`
}))
}
minHeight={200}
/>
</Card>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});
This is my components/SwipeListView.js
import React, { Component } from 'react';
import {
Animated,
Image,
StyleSheet,
TouchableOpacity,
TouchableHighlight,
View,
} from 'react-native';
import {
Avatar,
Button,
Text,
Title,
Subheading,
TouchableRipple,
withTheme,
} from 'react-native-paper';
import { SwipeListView as SwipeListViewDefault } from 'react-native-swipe-list-view';
/* eslint-disable react/prop-types, react/destructuring-assignment, react/no-access-state-in-setstate */
class SwipeListView extends Component {
leftBtnRatio = 0.25;
rightBtnRatio = 0.75;
constructor(props) {
super(props);
this.state = {
listType: 'FlatList',
listViewData: props.listViewData
.map((data, i) => ({ key: `${i}`, ...data })),
};
this.rowTranslateAnimatedValues = {};
props.listViewData
.forEach((data, i) => {
this.rowTranslateAnimatedValues[`${i}`] = new Animated.Value(1);
});
}
getStyles() {
const { minHeight, theme } = this.props;
const { colors } = theme;
return StyleSheet.create({
rowFrontContainer: {
overflow: 'hidden',
},
rowFront: {
alignItems: 'center',
backgroundColor: colors.surface,
borderBottomColor: colors.accent,
borderBottomWidth: 1,
justifyContent: 'center',
minHeight: '100%',
flex: 1,
},
rowBack: {
alignItems: 'center',
backgroundColor: colors.surface,
flexDirection: 'row',
justifyContent: 'space-between',
paddingLeft: 15,
minHeight: '100%',
},
backBtn: {
alignItems: 'center',
bottom: 0,
justifyContent: 'center',
position: 'absolute',
top: 0,
},
backLeftBtn: {
backgroundColor: colors.primary,
left: 0,
width: `${this.leftBtnRatio * 100}%`,
},
backRightBtn: {
backgroundColor: colors.accent,
right: 0,
width: `${this.rightBtnRatio * 100}%`,
},
});
}
onRowDidOpen = (rowKey) => {
console.log('This row opened', rowKey);
};
onSwipeValueChange = swipeData => {
const { dimensions } = this.props;
const { key, value } = swipeData;
if (value < -dimensions.width * this.rightBtnRatio && !this.animationIsRunning) {
this.animationIsRunning = true;
Animated.timing(this.rowTranslateAnimatedValues[key], {
toValue: 0,
duration: 200,
}).start(() => {
const newData = [...this.state.listViewData];
const prevIndex = this.state.listViewData.findIndex(item => item.key === key);
newData.splice(prevIndex, 1);
this.setState({listViewData: newData});
this.animationIsRunning = false;
});
}
};
closeRow(rowMap, rowKey) {
if (rowMap[rowKey]) {
rowMap[rowKey].closeRow();
}
}
deleteRow(rowMap, rowKey) {
this.closeRow(rowMap, rowKey);
const newData = [...this.state.listViewData];
const prevIndex = this.state.listViewData.findIndex(
(item) => item.key === rowKey,
);
newData.splice(prevIndex, 1);
this.setState({ listViewData: newData });
}
render() {
const { minHeight, dimensions, theme } = this.props;
const { colors } = theme;
const styles = this.getStyles();
return (
<SwipeListViewDefault
data={this.state.listViewData}
renderItem={data => (
<Animated.View
style={[styles.rowFrontContainer, {
height: this.rowTranslateAnimatedValues[data.item.key].interpolate({
inputRange: [0, 1],
outputRange: [0, minHeight],
})}]}
>
<TouchableRipple
onPress={() => console.log('You touched me')}
style={styles.rowFront}
underlayColor={colors.background}
>
<View>
<Title>{data.item.title}</Title>
<Text>
{data.item.description}
</Text>
</View>
</TouchableRipple>
</Animated.View>
)}
renderHiddenItem={(data, rowMap) => (
<View style={styles.rowBack}>
<TouchableOpacity
style={[
styles.backLeftBtn,
styles.backBtn,
]}
onPress={() => this.closeRow(rowMap, data.item.key)}
>
<Text>Tap pour annuler</Text>
</TouchableOpacity>
<TouchableOpacity
style={[
styles.backRightBtn,
styles.backBtn,
]}
onPress={() => this.deleteRow(rowMap, data.item.key)}
>
<Animated.View
style={[
styles.trash,
{
transform: [
{
scale: this.rowTranslateAnimatedValues[
data.item.key
].interpolate({
inputRange: [
45,
90,
],
outputRange: [0, 1],
extrapolate:
'clamp',
}),
},
],
},
]}
>
<Text>Swipe left to delete</Text>
</Animated.View>
</TouchableOpacity>
</View>
)}
leftOpenValue={dimensions.width * this.leftBtnRatio}
rightOpenValue={-dimensions.width * this.rightBtnRatio}
previewRowKey={'0'}
previewOpenValue={-40}
previewOpenDelay={3000}
onRowDidOpen={this.onRowDidOpen}
onSwipeValueChange={this.onSwipeValueChange}
recalculateHiddenLayout={true}
/>
);
}
}
export default withTheme(SwipeListView);
Expect
I expect when using recalculateHiddenLayout={true}, to get the hidden row height calculated dynamically
Result Screenshots
On the web, I am able to set the height:
but I when using iOS and Android, the height is forced.
Environment
OS: ios/android/web
RN Version: expo SDK36
How can I set the height of each row dynamically?
Important edit
The problem is the fixed value here in the animation:
height: this.rowTranslateAnimatedValues[data.item.key].interpolate({
inputRange: [0, 1],
outputRange: [0, 200], // <--- here
})}]}
I have replaced it in the example with props.minHeight:
height: this.rowTranslateAnimatedValues[data.item.key].interpolate({
inputRange: [0, 1],
outputRange: [0, this.props.minHeight],
})}]}
It doesn't permit dynamic height, how can I get the row height dynamically?

Declaring array for use in React Native AutoComplete search engine

Not sure where I go about declaring the array with which I want to search from, any assistance would be appreciated. I believe my issue is that I am declaring the "services' array in the incorrect area but I am not sure where else to put it! Or if the commas are the right character to be using in between strings/services
import React, { useState, Component } from 'react';
import { StyleSheet, StatusBar, View, Text, Button, TouchableOpacity } from 'react-native';
import AutoComplete from 'react-native-autocomplete-input';
class CareProviderSequenceScreen extends Component {
constructor (props) {
super (props);
this.state = {
services: [],
query: '',
}
}
render() {
const query = this.state;
const services = {
"Pick up my Prescription",
'Pick up groceries',
'Pick up dry cleaning',
'Pick up my pet',
}
return (
<View style={styles.container}>
<Autocomplete
autoCapitalize="none"
autoCorrect={false}
containerStyle={styles.autocompleteContainer}
//data to show in suggestion
data={services.length === 1 && comp(query, services[0].title) ? [] : services}
//default value if you want to set something in input
defaultValue={query}
/*onchange of the text changing the state of the query which will trigger
the findFilm method to show the suggestions*/
onChangeText={text => this.setState({ query: text })}
placeholder="Enter your need"
renderItem={({ item }) => (
//you can change the view you want to show in suggestion from here
<TouchableOpacity onPress={() => this.setState({ query: item.title })}>
<Text style={styles.itemText}>
{item.title} ({item.release_date})
</Text>
</TouchableOpacity>
)}
/>
<View style={styles.descriptionContainer}>
{services.length > 0 ? (
<Text style={styles.infoText}>{this.state.query}</Text>
) : (
<Text style={styles.infoText}>Enter The Film Title</Text>
)}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#F5FCFF',
flex: 1,
padding: 16,
marginTop: 40,
},
autocompleteContainer: {
backgroundColor: '#ffffff',
borderWidth: 0,
},
descriptionContainer: {
flex: 1,
justifyContent: 'center',
},
itemText: {
fontSize: 15,
paddingTop: 5,
paddingBottom: 5,
margin: 2,
},
infoText: {
textAlign: 'center',
fontSize: 16,
},
});
export default CareProviderSequenceScreen ;
CareProviderSequenceScreen .navigationOptions = () => ({
title: "Home & Personal Care",
headerTintColor: '#9EBBD7',
headerStyle: {
height: 65,
backgroundColor: '#1E5797',
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.20,
shadowRadius: 1.41,
elevation: 2,}
});
First, you are assigning an object to services array.
Second, you are not accessing the query state properly. It should be
const { query } = this.state

List item for chat from Array inside array React Native

This is my code for Chat Box, the window where I have "In" and "Out" messages are appearing.
import React, { Component } from "react";
import {
StyleSheet,
Text,
View,
TouchableOpacity,
TextInput,
FlatList,
Platform,
AsyncStorage
} from "react-native";
import Tutor from "../image/krutika.jpg";
import {
Container,
Header,
Left,
Input,
Body,
Right,
Thumbnail,
Button
} from "native-base";
import FontAwesome from "react-native-vector-icons/FontAwesome";
import Ionicons from "react-native-vector-icons/Ionicons";
import Icon1 from "react-native-vector-icons/FontAwesome";
import axios from "axios";
export default class ChatBox extends Component {
static navigationOptions = {
header: null
};
state = {
group_msgs: [],
student_id: null
};
renderDate = date => {
return <Text style={styles.time}>{date}</Text>;
};
componentWillMount = () => {
this.loading();
const { navigation } = this.props;
groupName = navigation.getParam("groupName");
group_id = navigation.getParam("group_id");
};
loading = async () => {
const userid = await AsyncStorage.getItem("user_id");
this.state.student_id = userid;
try {
let { data } = await axios.get('https://www.qualpros.com/chat/imApi/getMessage?groupId=6&limit=10&start=0&userId=62').then(response => {
// console.log(response)
if (response.status == 200) {
this.setState({ group_msgs: response.data.response.message });
console.log(response.data.response)
} else {
}
});
} catch (err) {
console.log(err);
}
};
render() {
return (
<Container>
<Header style={{ backgroundColor: "#d91009" }}>
<Left style={{ flex: 1, flexDirection: "row" }}>
<TouchableOpacity
style={styles.backArrow}
onPress={() => this.props.navigation.navigate("ChatScreen")}
>
<FontAwesome name="angle-left" size={30} color="#fff" />
</TouchableOpacity>
<Thumbnail
source={Tutor}
style={{
marginLeft: 8,
width: 30,
height: 30,
borderRadius: 30 / 2
}}
/>
</Left>
<Body>
<Text
onPress={() => {
this.props.navigation.navigate("Groupmembers", {
group_id:group_id,
groupname:groupName,
});
}}
style={{
alignSelf: Platform.OS == "android" ? "center" : null,
fontSize: 17,
color: "#fff"
}}
>
{groupName}
</Text>
</Body>
<Right>
<Button
style={{ backgroundColor: "#d91009" }}
onPress={() => {
this.props.navigation.navigate("TutorCalender");
}}
>
<Icon1 active name="calendar" size={24} color="#FFF" />
</Button>
</Right>
</Header>
<View style={styles.container}>
<FlatList
style={styles.list}
data={this.state.group_msgs}
keyExtractor={item => {
return item.m_id;
}}
renderItem={message => {
console.log(item);
const item = message.item;
let inMessage = (item.sender === this.state.userid) ? 'in' : 'out';
let itemStyle = inMessage ? styles.itemIn : styles.itemOut;
return (
<View style={[styles.item, itemStyle]}>
<View style={[styles.balloon]}>
<Text>{item.message}</Text>
</View>
</View>
);
}}
/>
<View style={styles.footer}>
<View style={styles.inputContainer}>
<TextInput
style={styles.inputs}
placeholder="Write a message..."
underlineColorAndroid="transparent"
onChangeText={name_address => this.setState({ name_address })}
/>
</View>
{/* <TouchableOpacity style={styles.btnSend}>
<Ionicons name="md-send" size={36} color='#d91009' /> style={styles.iconSend} />
</TouchableOpacity> */}
</View>
</View>
</Container>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
list: {
paddingHorizontal: 17
},
footer: {
flexDirection: "row",
height: 60,
backgroundColor: "#eeeeee",
paddingHorizontal: 10,
padding: 5
},
btnSend: {
//color: "#d91009",
width: 40,
height: 40,
borderRadius: 360,
alignItems: "center",
justifyContent: "center"
},
iconSend: {
width: 30,
height: 30,
alignSelf: "center"
},
inputContainer: {
borderBottomColor: "#F5FCFF",
backgroundColor: "#FFFFFF",
borderRadius: 30,
borderBottomWidth: 1,
height: 40,
flexDirection: "row",
alignItems: "center",
flex: 1,
marginRight: 10
},
inputs: {
height: 40,
marginLeft: 16,
borderBottomColor: "#FFFFFF",
flex: 1
},
balloon: {
maxWidth: 250,
padding: 15,
borderRadius: 20
},
itemIn: {
alignSelf: "flex-start",
backgroundColor: "#eeeeee"
},
itemOut: {
alignSelf: "flex-end",
backgroundColor: "#DCF8C5"
},
time: {
alignSelf: "flex-end",
margin: 15,
fontSize: 12,
color: "#808080"
},
item: {
marginVertical: 14,
flex: 1,
flexDirection: "row",
borderRadius: 300,
padding: 1
}
});
I am using axios to fetch the api, the api response is coming as an Array inside the array but nothing is coming on the screen.
I can get it with storing response upto message but then I can't have the loop on messages.
Please help.
Thanks in advance
When doing a GET request to the endpoint in your code the response looks as follows:
{
"status":{
"code":200,
"message":"Success"
},
"totalMessage":6,
"recentMessageId":228,
"response":[
...
]
}
Inside the response object there's an array of message objects so you can't use response.data.response.message when setting state. That part of your code needs to be:
this.setState({ group_msgs: response.data.response });
Now you should be able to iterate through the group_msgs object to get the message key value for each item in the array.
Also in the FlatList component you should have
keyExtractor={item => {
return item.message.m_id;
}}
Your renderItem seems to be wrong as well, see should be something like this:
renderItem={ ({item}) => {
let inMessage = (item.sender.usedId === this.state.userid) ? 'in' : 'out';
let itemStyle = inMessage ? styles.itemIn : styles.itemOut;
return (
<View style={[styles.item, itemStyle]}>
<View style={[styles.balloon]}>
<Text>{item.message.message}</Text>
</View>
</View>
);
}}
I strongly suggest you take a look at the structure of the response object since that's where you are failing at the moment.

Categories

Resources