how to json data fix render in react native - json

I am really a beginner.
in renderItem ()
If {item.value} is 10 or less, I want to render the output as "Text".
How can I do this?
Thank you for reading the question. I will study hard
I pray that you will be safe and healthy from the corona virus.
renderItem = ({item}) => {
return(
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<View style={{marginBottom:10}}>
<Text>
{item.from}
{item.to}
{item.value}
</Text>
</View>
</View>
)
}
componentDidMount(){
const url = 'http://api-ropsten.etherscan.io/api?module=account&action=txlist&address=0x3A19E068Ea11b4D10D4516823eA9482fE70F1c52&startblock=0&endblock=99999999&sort=asc&apikey=IQN5KP8AKJ9WFTYNGZRJE7W3QHXPT4S65H'
fetch(url)
.then((response)=>response.json())
.then((responseJson) => {
this.setState({
dataSource:responseJson.result
})
})
.catch((error)=>{
console.log(error)
})
}
render(){
return(
<View style={{flex:1,justifyContent:'center', alignItems:'center'}}>
<FlatList
data={this.state.dataSource}
renderItem={this.renderItem}
/>
</View>
)
}
}

you need learn javascript and es6 specially, will help you a lot in future. For now you can check in renderItem method if value is less than 10 or not and then return the desired output.
renderItem = ({item}) => {
if(item.value < 10){
return(
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<View style={{marginBottom:10}}>
<Text>
{The text you want}
</Text>
</View>
</View>)
} else {
return <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<View style={{marginBottom:10}}>
<Text>
{some value}
</Text>
</View>
</View>
}

Related

How to Fetch Data from Firebase Realtime Database in React Native App

How can I fetch data from Firebase Realtime Database using the below method?
My Realtime Database:
import React, { useEffect, useState, useContext, } from 'react';
import { View, Text, Image, StyleSheet, ScrollView, SafeAreaView, ActivityIndicator, FlatList, } from 'react-native';
import {firebase} from '../config';
export default function App() {
const [users, setUsers] = useState([]);
const todoRef = firebase.firestore().collection('testing');
useEffect(() => {
todoRef.onSnapshot(
querySnapshot => {
const users = []
querySnapshot.forEach((doc) => {
const { one, two, three, four
} = doc.data()
users.push({
id: doc.id,
one, two, three, four
})
})
setUsers(users)
}
)
}, [])
return (
<View style={{ backgroundColor: theme.viewOne, }}>
{isLoading ? <ActivityIndicator /> : (
<FlatList
ListHeaderComponent={
<Image source={require('./AllImage/qq2.jpg')}
style={{ width: "auto", height: 150, resizeMode: "cover", }} />
}
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<View style={styles.container}>
<View style={styles.item}>
<Text style={styles.mainText}>{item.one}</Text>
</View>
<View style={styles.item}>
<Text style={styles.mainText}>{item.two}</Text>
</View>
</View>
)}
/>
)}
</View>
);
};
Rahul for react-native you can implement it like this instead of using async-await.
You need to connect your app to database like this -
import { firebase } from '#react-native-firebase/database';
const reference = firebase
.app()
.database('https://<databaseName>.<region>.firebasedatabase.app/')
.ref('/users/123');
Then you can perform read-write transactions like this -
import database from '#react-native-firebase/database';
database()
.ref('/users/123')
.once('value')
.then(snapshot => {
console.log('User data: ', snapshot.val());
});
The article has a detailed implementation and you can choose to persist data easily as well. Hope it helps!

How to pass json array to Listview In react Native

He I am trying to implement Listview in React Native.I followed official docs but that to no success.Basically i get response from database about actor Names and their respective last name as follows
[
{"Name":"Amitabh","LastName":"Bachchan"},
{"Name":"Jaya","LastName":"Bhaduri Bachchan"},
{"Name":"Hrithik","LastName":"Roshan"},
{"Name":"Shahrukh","LastName":"Khan"},
{"Name":"Akshay","LastName":"Kumar"},
]
So I wanted to display these list using listview.
.
this is my code so far
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource:ds.cloneWithRows(['row 1', 'row 2']),
};
}
componentDidMount() {
//this is where i get data from previous screen as i mentioned in above format then i pass to state
this.setState({
dataSource: this.props.source,
})
}
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) =>
<View
style={styles.CanContainer}>
<View
style={styles.CanSubContainer}>
<View style={{flex: 1, alignItems: 'center'}}>
<Text style={styles.canTitles}>
{rowData.Name}
</Text>
</View>
<View style={{flex: 1, alignItems: 'center'}}>
<Text style={styles.canTitles}>
{rowData.LastName}
</Text>
</View>
</View>
</View>
}
/>
following is what i tried but i am getting error as
You can't assign your data directly to your listview datasource. Change your constructor and move your listview data source to global state. Also you can't assign JSON to listview datasource. You have to convert your JSON response to javascript object/array. You can use JSON.parse() function for this.
const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
export default class Example extends Component {
constructor(props) {
super(props)
const myData = JSON.parse(props.source);
this.state = {
dataSource: ds.cloneWithRows(myData),
}
}
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) =>
<View
style={styles.CanContainer}>
<View
style={styles.CanSubContainer}>
<View style={{ flex: 1, alignItems: 'center' }}>
<Text style={styles.canTitles}>
{rowData.Name}
</Text>
</View>
<View style={{ flex: 1, alignItems: 'center' }}>
<Text style={styles.canTitles}>
{rowData.LastName}
</Text>
</View>
</View>
</View>
}
/>
);
}
}

Why can't I display my items in Flatlist?

I am currently trying to learn React-Native atm and I am having some trouble displaying out my items in my FlatList.
The below is my code
import React from 'react';
import { FlatList, ActivityIndicator, Text, View } from 'react-native';
export default class FetchExample extends React.Component {
constructor(props){
super(props);
this.state = {
isLoading: true,
dataSource: []
}
}
componentDidMount(){
return fetch('https://api.coindesk.com/v1/bpi/currentprice.json')
.then((res) => res.json())
.then((resJson) => {
console.log('Here are the stuff', resJson.bpi)
this.setState({
isLoading: false,
dataSource: resJson.bpi,
})
})
// catch any potential errors here
.catch((error) =>{
console.log(error)
})
}
render(){
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator />
</View>
);
}
return(
<View style={{flex: 0.5, padding: 20}}>
<Text>{console.log(this.state.dataSource)}</Text>
<Text>Here's some testing text</Text>
<Text>{console.log("This is in this.state.dataSource", this.state.dataSource)}</Text>
{/* <FlatList
data= {this.state.dataSource}
renderItem = {({item}) => <Text>{console.log(item)}</Text>}
/> */}
</View>
)
}
}
Whenever I uncomment the FlatList the simulator will shoot me an error saying "Invariant Violation: Tried to get frame for out of range index NaN"
What am I doing wrong? Atm I am just trying to see what's in item and get an understanding of how to work with Flatlist
here how i do it
<FlatList
data={[this.state.dataSource]}
renderItem={({ item }) => this._renderListItem(item)}
/>
and here the _renderListItem()
_renderListItem(item){
console.log(item)
return(
<View>
<View style={{flexDirection:'row',width:'100%',backgroundColor:'red'}}>
<Text>{item.USD.code}</Text>
<Text>{item.USD.symbol}</Text>
<Text>{item.USD.description}</Text>
</View>
</View>
)
}
and here is the expo link click here you get the idea
and if any questions you have please ask me ...

Putting a variable inside render() return - React Native

I am mapping json data and can console.log my result, but I can't insert those values in the render.
Here is the code I have for my render:
data_use = responseJson;
const result_id = data_use.map(function(val) {
return val.id;
}).join(',');
console.log(result_id);
render(){
return(
<View style = { styles.MainContainer }>
<View>
<Card>
<View>
<Text>{result_id}</Text>
</View>
</Card>
</View>
</View>
);
}
The error that I am getting is ReferenceError: result_id is not defined. Which is odd because it is defined?
This approach will be useful if the data is loaded from a server.
constructor(props) {
super(props);
this.state = {
data : []
};
}
componentDidMount() {
// Your code to fetch data from server
this.setState({ data: your_array_from_fetch });
}
render(){
return(
<View style={ styles.MainContainer }>
<View>
<Card>
<View>
{
this.state.data.length > 0 ?
this.state.data.map((val, index) => {
return (
<Text key={index}>val.id</Text>
);
} ).join(',');
: null
}
</View>
</Card>
</View>
</View>
);
}
I made few assumption from my side and I believe this is what you want! If any issue write that down below.
EDIT:
Yoganode issue can be fixed by testing if the data array length is greater than zero. This usually happens when render does not return anything.
I used componentDidMount instead of componentWillMount because componentWillMount is deprecated.
Try this conditional render
{
this.state.data.length > 0 ?
this.state.data.map((val, index) => {
if (some_var == another_var) {
return (
<Text key={index}>val.id</Text>
);
}
}).join(',');
: null
}
Everything you did is correct but variable you declared outside render? How can it be accessed in render
render(){
//considering array of objects in "data_use" state
const result_id = this.state.data_use.map(function(val) {
return val.id;
}).join(',');
return(
<View style = { styles.MainContainer }>
<View>
<Card>
<View>
<Text>{result_id}</Text>
</View>
</Card>
</View>
</View>
);
}

How do I get the json nested object?

I am new to React Native, and want to get the nested object from json. Here is my code. And I can get succesfuly data.phone but always get this if I try to get data.name.title or etc.
undefined is not an object
Here is my code.
class Dictionary extends Component {
// Initialize the hardcoded data
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows([
'John', 'Joel', 'James', 'Jimmy', 'Jackson', 'Jillian', 'Julie', 'Devin'
])
};
fetch('http://api.randomuser.me/?results=50')
.then((response) => response.json())
.then((responseJson) => {
//return responseJson.movies;
console.log( responseJson.results );
this.setState({
dataSource: ds.cloneWithRows(responseJson.results),
loaded:false,
})
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<View
style={styles.container}>
<ListView
dataSource={this.state.dataSource}
renderRow={(data) =>
<View>
<Text>
{data.phone}
</Text>
<Text>
{data.name.title}
</Text>
</View>
}
renderSeparator={(sectionId, rowId) => <View key={rowId} style={styles.separator} />}
/>
</View>
);
}
}
How can I get the name.title?
Thanks
And here is the json data from randomuser.me
{"results":[{"gender":"female","name":{"title":"miss","first":"abby","last":"perkins"},"location":{"street":"9542 highfield road","city":"ely","state":"herefordshire","postcode":"J9 2ZJ"},"email":"abby.perkins#example.com","login":{"username":"redcat541","password":"1026","salt":"LIsOByBg","md5":"2890bf50a87289f7f3664840e2c47fe3","sha1":"1944896ba6cc78ad32dcf927dc5c9226d2f9e050","sha256":"9013be19c91195788009cc545f8a2be4494687dc29b155513022ce9157b73785"},"dob":"1959-05-20 07:03:41","registered":"2006-07-10 01:28:56","phone":"0101 716 4694","cell":"0738-649-138","id":{"name":"NINO","value":"BC 35 80 42 Q"},"picture":{"large":"https://randomuser.me/api/portraits/women/54.jpg","medium":"https://randomuser.me/api/portraits/med/women/54.jpg","thumbnail":"https://randomuser.me/api/portraits/thumb/women/54.jpg"},"nat":"GB"}],"info":{"seed":"2e632bbc13c85cb2","results":1,"page":1,"version":"1.1"}}
when I console.log(data.name) I get this {"title":"miss","first":"abby","last":"perkins"} and so on on every Iteration i get different names. So i guess there is no need in data[0] - it looks like everything is ok with getting the proper data object. just need to access data.name.title but no luck with it. Sorry, it pretty confusing for me this time as every prev time there were no problems with any json obj or array
This is caused by the constructor, but I don't know why.
Just pass an empty array and it will work.
this.state = {
dataSource: ds.cloneWithRows([])
};
You can do this too:
this.state = {
dataSource: ds.cloneWithRows([{name: "Ahmed"}])
};
See here for more information:
https://facebook.github.io/react-native/docs/listviewdatasource.html#clonewithrows
Its because your {data.name.title} is directly in view tag. Place that in <Text> component like this:
<ListView
dataSource={this.state.dataSource}
renderRow={(data) =>
<View>
<Text>
{data.phone}
</Text>
<Text>
{data.name.title}
</Text>
</View>
}
renderSeparator={(sectionId, rowId) => <View key={rowId} style={styles.separator} />}
/>