React Native: Json not showing in Screen: Getting Error in Console - javascript

I am getting this error when trying to bring JSON data from mongodb into screen of React Native Application. Screen is showing, just no data. Error is below with code. This is simple hello world app and I am trying to bring in some json data from mongodb to the screen. I am just not sure of the correct setup, though I do have the screen visible up to choose your listing in Listings.js file. for some reason the network is not working. Not sure if I need to proxy in package.json?
App.js
import React, {Component} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import {Listings} from './src/Listings';
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<View style={{flex: 1}}>
<Text style={styles.welcome}>Air BNB Data Screen</Text>
<View style={{flex: 1, borderWidth: 3, borderColor: 'blue'}}>
<Listings></Listings>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
src
Listings.js
import React from 'react';
import {StyleSheet, View, FlatList, Text} from 'react-native';
import axios from 'axios';
export class Listings extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
show: true,
};
}
componentDidMount = () => {
const options = {
headers: {'Content-Type': 'application/json'},
};
axios
.get('http://localhost:8080/api/Listings/10006546', options)
.then((response) => {
this.setState({
data: [],
});
console.log(data)
})
.catch((error) => {
console.log(error);
});
};
renderRow = ({item}) => {
return (
<View containerStyle={{ elevation: 1, borderRadius: 15 }}>
<View row>
<View flex={2}>
<Text h4>{item._id}</Text>
</View>
</View>
</View>
)
}
render() {
return (
<View style={styles.container}>
<Text h3 style={{ marginLeft: 10 }}>Choose your Listing!</Text>
<View>
<FlatList
style={{ marginHorizontal: 10, marginTop: 10 }}
data={this.state.data}
renderItem={this.renderRow}
keyExtractor={(item, index) => item._id}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
fontSize: 12,
textAlign: 'center',
margin: 5,
},
});
Error in console - This is the error that I am receiving in the console.
Error: Network Error at createError (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\axios\lib\core\createError.js:16)
at EventTarget.handleError (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\axios\lib\adapters\xhr.js:83)
at EventTarget.dispatchEvent (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\event-target-shim\dist\event-target-shim.js:818)
at EventTarget.setReadyState (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:575)
at EventTarget.__didCompleteResponse (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:389)
at C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:502
at RCTDeviceEventEmitter.emit (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189)
at MessageQueue.__callFunction (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425)
at C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112
at MessageQueue.__guard (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373
)

The solve for this was fairly simplistic. I ended up doing some searching, but I was able to find a fix. Instead of using localhost, I was able to use 10.0.2.2 instead. This fixed the network error, however, I do have a data is not defined error now.

Related

How to play/listen buffer chunks in react native?

I am trying to create an app in react native to speak in microphone and listen at the same time.
I tried the react-native-live-audio-stream package which streams the microphone.
Here is the sample code:
import React, { Component } from 'react';
import { View, SafeAreaView } from 'react-native';
import { NativeBaseProvider, Button} from 'native-base';
import LiveAudioStream from 'react-native-live-audio-stream';
import { Buffer } from 'buffer';
export default class TestMic extends Component {
startListenToMic(){
LiveAudioStream.init({
sampleRate: 32000,
channels: 1,
bitsPerSample: 16,
audioSource: 6,
bufferSize: 4096
});
LiveAudioStream.on('data', data => {
let chunk = Buffer.from(data, 'base64'); // => What I am supposed to do with this data to listen them?
console.log(chunk)
})
LiveAudioStream.start();
}
stopListenToMic(){
LiveAudioStream.stop();
}
render(){
return(
<NativeBaseProvider>
<SafeAreaView style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<View style={{flexDirection: 'row'}}>
<Button
onPress={ () => this.startListenToMic() }
mr={3}
>Start</Button>
<Button
onPress={ () => this.stopListenToMic() }
ml={3}
>Stop</Button>
</View>
</SafeAreaView>
</NativeBaseProvider>
)
}
}
and this is the data log in console:
Console Log
What is the best way to convert data to audio and listen ?

react-native NumericInput component doesn't work on web browser

On the web browser, I have the + and - overlapping and clicking on them doesn't do anything. Also we can't see the number.
So I tried to run it on android and it worked properly.
But why isn't it working on the web browser ?
The code is however basic.
import React from 'react';
import { View, Text, Buttonn, FlatList } from 'react-native';
import NumericInput from 'react-native-numeric-input'
const style = require('#app/components/common/styles').style;
export default class HomeSettingsScreen extends React.Component {
constructor(props) {
super(props);
this.navigation = props.navigation;
this.state = {
homeCitiesNumber: 10,
}
}
render = () => {
return (
<View>
<View style={style.container}>
<View style={{ flexDirection: 'row', backgroundColor: 'black', width: '100%', fontFamily: 'DMSans-Regular' }}>
<Text style={style.titleContainer}>Settings</Text>
</View>
</View>
<NumericInput
value={this.state.homeCitiesNumber}
onChange={value => this.setState({homeCitiesNumber: value})}
minValue={0}
maxValue={25}
/>
<NumericInput onChange={value => console.log(value)} />
</View>
)
}
}

there is a way to fix "Warning: Each child in a list should have a unique "key"?

Is there a way to fix this warning?
Warning: Each child in a list should have a unique "key
I got this warning every time and don't understand how to fix it.
I try to fix it but i realize that something wrong in my way .
hope to understand whats wrong because its so annoying.
import React, { Component } from 'react';
import { View, Text, StyleSheet, ActivityIndicator, Platform, FlatList, Dimensions, Image } from 'react-native';
import { HeaderButtons, Item } from 'react-navigation-header-buttons'
import HeaderButton from '../components/HeaderButton';
import axios from 'axios';
const { width, height } = Dimensions.get('window');
export default class PlacesListScreen extends Component {
constructor(props) {
super(props);
this.state = { isLoading: true, data: [] };
}
componentDidMount() {
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then(res => {
this.setState({
isLoading: false,
data: res.data,
})
console.log(res.data);
})
}
renderItem(item) {
const { title, artist } = item.item;
return (
<View style={styles.itemView}>
<View style={styles.imgContainer}>
{/* <Image style={styles.imageStyle}
source={{ uri: image }}
/> */}
</View>
<View style={styles.itemInfo}>
<Text style={styles.name}>
{title+ ' ' + artist}
</Text>
<Text style={styles.vertical} numberOfLines={1}>{title} |</Text>
</View>
</View>
);
}
render() {
if (this.state.isLoading) {
return (
<View style={{ flex: 1, padding: 20 }}>
<Text style={{ alignSelf: 'center', fontWeight: 'bold', fontSize: 20 }}>loading...</Text>
<ActivityIndicator />
</View>
)
}
return (
<View style={styles.container}>
<FlatList
data={this.state.data}
renderItem={this.renderItem.bind(this)}
keyExtractor={item => item.id}
/>
</View>
);
}
}
Hope that you understand my problem and how can I fix it.
the example code above shows my try to get some data from API, but it returns a warning every time about
each child in a list should have a unique "key".
console.log the key of each item. It may be possible u have the same id for some items?

How to render a loader until data is fetched in React Native

I am fetching data through an async request. I know that I need to wait for the api request to complete before displaying the data. Unfortunately, I'm not sure how to create a loader to wait for the data to load.I am new to react, so if I could also get help with implementing it as well, that would be fantastic! Here is my current code:
import React, { Component, PropTypes } from 'react';
import { View, Text, ListView, StyleSheet, TouchableHighlight} from 'react- native';
import Header from '../Components/Header';
import Api from '../Utility/Api';
export default class CalendarPage extends Component {
constructor(props) {
super(props);
}
async componentWillMount() { this.setState(
{data: await Api.getDates()},
)
}
render() {
return (
<View style={{flex: 1}}>
<Header pageName="Calendar" navigator={this.props.navigator}/>
<View style = {{flex:9}}>
<View>
{ this.state.data.days[0].items.map((item) => (
<View>
<Text>{item.summary}</Text>
<Text>{item.start.dateTime}</Text>
<Text>{item.description}</Text>
</View>
))}
</View>
</View>
</View>
);
}
}
A simple example using ActivityIndicator -
import ActivityIndicator
import { View, Text, ListView, StyleSheet, TouchableHighlight, ActivityIndicator} from 'react- native';
set data state to null
constructor(props) {
super(props);
this.state = {
data: null
}
}
do conditional rendering
render() {
if (!this.state.data) {
return (
<ActivityIndicator
animating={true}
style={styles.indicator}
size="large"
/>
);
}
return (
<View style={{flex: 1}}>
<Header pageName="Calendar" navigator={this.props.navigator}/>
....
....
</View>
);
}
}
indicator style
const styles = StyleSheet.create({
indicator: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
height: 80
}
});
Although solution proposed by #vinayr works fine but user will still be able to click on screen and perform some action even while loader is being shown which can lead to crash.
One solution is wrap loader inside a Modal.
import React, { Component } from 'react';
import {
StyleSheet,
View,
Modal,
ActivityIndicator,
} from 'react-native';
const styles = StyleSheet.create({
modalBackground: {
flex: 1,
alignItems: 'center',
flexDirection: 'column',
justifyContent: 'space-around',
backgroundColor: '#00000040',
},
activityIndicatorHolder: {
backgroundColor: '#FFFFFF',
height: 100,
width: 100,
borderRadius: 10,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-around',
},
});
const SmartLoader = (props) => {
const {
isLoading,
...attributes
} = props;
return (
<Modal
transparent
animationType={'none'}
visible={isLoading}
onRequestClose={() => { console.log('Noop'); }}
>
<View style={styles.modalBackground}>
<View style={styles.activityIndicatorHolder}>
<ActivityIndicator
animating={isLoading}
size="large"
/>
</View>
</View>
</Modal>
);
};
export default SmartLoader;
After that you can use it anywhere in your component, user will not be able to perform any action till loader is finished ( made hidden based on flag)

How to navigate page with React Native

I have a component for listing items, I want to add the function that can go to a different page, and that page has the detail about that item. Currently, this is my code for listing items.
import React, { Component } from 'react';
import { ScrollView } from 'react-native';
import axios from 'axios';
import CarDetail from './CarDetail';
const API_URL = 'http://localhost:3000';
class CarList extends Component {
state = { cars: [] };
componentWillMount() {
console.log('Mount');
axios.get(`${API_URL}/cars`)
.then(response => this.setState({ cars: response.data.cars }));
}
renderCars() {
return this.state.cars.map(car => <CarDetail key={car.id} car={car} />
);
}
render() {
console.log(this.state.cars);
return (
<ScrollView>
{this.renderCars()}
</ScrollView>
);
}
}
export default CarList;
and this is the code for describing items
import React from 'react';
import { Text, View, Image } from 'react-native';
import { Actions } from 'react-native-router-flux';
import Card from '../material/Card';
import CardSection from '../material/CardSection';
const CarDetail = ({ car }) => {
const imageURI = 'https://yt3.ggpht.com/-HwO-2lhD4Co/AAAAAAAAAAI/AAAAAAAAAAA/p9WjzQD2-hU/s900-c-k-no-mo-rj-c0xffffff/photo.jpg';
const { make, model } = car;
function showCarDetail() {
Actions.showCar();
}
return (
<Card>
<CardSection>
<View style={styles.containerStyle}>
<Image
style={styles.imageStyle}
source={{ uri: imageURI }}
/>
</View>
<View style={styles.headContentStyle}>
<Text
style={styles.headerTextStyle}
onPress={showCarDetail()}
>
{make}
</Text>
<Text>{model}</Text>
</View>
</CardSection>
<CardSection>
<Image
style={styles.picStyle}
source={require('./car.jpg')}
/>
</CardSection>
</Card>
);
};
const styles = {
headContentStyle: {
flexDirection: 'column',
justifyContent: 'space-around'
},
headerTextStyle: {
fontSize: 18
},
imageStyle: {
height: 50,
width: 50
},
containerStyle: {
justifyContent: 'center',
alignItems: 'center',
marginLeft: 10,
marginRight: 10
},
picStyle: {
height: 300,
flex: 1,
width: null
}
};
export default CarDetail;
How can I change my code for that? Can anyone give me an example?
You have to use some sort of navigation component. There are many out there, but personally I use the one that is built into React Native. https://facebook.github.io/react-native/docs/navigator.html

Categories

Resources