React native json parsing through Mysql - mysql

I am new to react-native. I need to display my JSON into my react native main page but I am not sure how to. Do you have any suggestions espiclay that the Json file is long. I want to display only "s_title":"hjkjhjk","s_description":"jnkmjhnkl" in an altarntive list view
JSON
Array [
Object {
"fk_c_locale_code": "en_US",
"fk_i_item_id": 3,
"s_description": "jnkmjhnkl",
"s_title": "hjkjhjk",
},
My Main React-Native page is the following where I need it to read from the Json file that:
import {
Button,
Alert
}
HomeScreen.navigationOptions = {
header: null,
};
function test(){
fetch('http://***:3000/users')
.then(response => response.json())
.then(users => console.warn(users));
//Alert.alert(response);
}

The code below that worked. No need for parsing or anything!
The source was the networking info section at react-native page.
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, FlatList} from 'react-native';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
android:
'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
dataSource:[]
};
}
componentDidMount(){
fetch("http://*****:3000/users")
.then(response => response.json())
.then((responseJson)=> {
this.setState({
dataSource: responseJson
})
})
.catch(error=>console.log(error)) //to catch the errors if any
}
render(){
return(
<View style={{padding:10}}>
<FlatList
padding ={30}
data={this.state.dataSource}
renderItem={({item}) =>
<View style={{height: 50}}>
<Text style={{height: 50}}>{item.s_description}</Text>
<Text style={{height: 50}}>{item.s_title}</Text>
<View style={{height: 1,backgroundColor:'gray'}}></View>
</View>
}
/>
</View>
)}
}

The easiest way would be your jsonobject[0].s_title and jsonobject[0].s_description.
Do check if it is undefined before assigning it; something like:
title = jsonobject[0].s_title === undefined ? "" : jsonobject[0].s_title

Related

small issue in react-native | ActivityIndicator | component | props inside a component | props | setState

so my issue is that i need to set a State inside a function/component.
the State "isLoading" is set to true by default (it's for the ActivityIndicator ) and i need to change it back to false inside the component so that the indicator stops working and the component renders the results.
here is code:
const Data = require('../data/my_data.json');
export default class Albums extends React.Component {
constructor(props) {
super(props);
this.state = {
Data_list : Data,
isLoading: true,
};
componentWillMount() {
return this.state.Data_list.map(something=> (
<list_Detail key={something.id} something={something} />
));
}
render() {
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return (
<ScrollView>{this.componentWillMount()}</ScrollView>
)}
}
i have already tried this:
componentWillMount() {
return this.state.Data_list.map(something=> (
<list_Detail key={something.id} something={something} />
))
.then(this.setState({isLoading: false}));
}
but it didn't work
SO ANY IDEAS !!!!????
componentWillMount is a lifecycle method, that is called right before the component is rendered. You cannot return UI from this method
Move UI part to render method and keep only the api call in componentWillMount.
componentWillMount() {
axios.get('https://api.jsonbin.io/b/5d05c8712132b7426d0')
.then(response => this.setState({Data: response.data, isLoading: false}));
));
}
In render method,
render(){
return (
//other UI
{this.state.Data.map(something => (
<list_Detail key={something.id} something={something} />
/>
))}
}
Find the usage for componentWillMount and other lifecycle methods here

React-native: how to get JSON from backend and put the objects in react-native elements, such as Text?

I am trying to fetch JSON data from a php file, which seems to work fine; I can alert values from the JSON. But I want to be able to put these values on the mobile app screen in Text elements or whatever. And I want this to happen when the screen opens, not when a button is pressed. So I made a function that fetches the JSON and I'm trying to return a value in Text elements. This function is called from the rendering. I don't get error messages, but it isn't working. Nothing shows up.
Here is the code:
import React, { Component } from 'react';
import { View, Text, AsyncStorage, Alert } from 'react-native';
import { UsersMap } from '../UsersMap';
import { PrimaryButton } from '../Buttons';
import styles from './styles';
class RestOptions extends Component {
getSearchResults() {
fetch('http://192.168.1.3/Restaurant_App/php/search_results.php')
.then((response) => response.json())
.then((responseJson) => {
var JSON_Test = responseJson["distance"][0];
//Alert.alert(JSON_Test);
return (
<View>
<Text>{JSON_Test}</Text>
</View>
);
}).catch((error) => {
console.error(error);
});
}
setReservation = () => {
this.props.navigation.navigate('SetReservation');
};
render() {
return (
<View>
<UsersMap />
{this.getSearchResults()}
<PrimaryButton
label="Set Reservation"
onPress={() => this.setReservation()}
/>
</View>
);
}
};
export default RestOptions;
This is what happens. The JSON value should appear between the map and the button:
Search Results Screen
First of all, in order to fetch the data as the screen opens, you should use the lifecycle method componentWillMount, which executes before the first render, and then store the result in the component's state. React docs on state and lifecycle
class RestOptions extends Component {
constructor(props) {
super(props);
this.state = {
jsonTest: null
}
}
componentWillMount() {
this.getSearchResults();
}
getSearchResults() {
fetch('http://192.168.1.3/Restaurant_App/php/search_results.php')
.then((response) => response.json())
.then((responseJson) => {
var JSON_Test = responseJson["distance"][0];
//Alert.alert(JSON_Test);
this.setState({ jsonTest: JSON_Test });
}).catch((error) => {
console.error(error);
});
}
//...
Then you can display the value on the render() method:
render() {
return (
<View>
<UsersMap />
<Text>{this.state.jsonTest}</Text>
<PrimaryButton
label="Set Reservation"
onPress={() => this.setReservation()}
/>
</View>
);
}
If the response is an array of values, you can use map() to display each of them in their own Text element:
{this.state.jsonTest.map((value, index) => <Text key={index}>{value}</Text>)}

How to get a specific item of a Flatlist in React-Native

How can I only render the item in a FlatList if the item.id is the same like the id in the json?
I'm new to react-native and JavaScript so maybe it's a stupid question.
My Code so far:
export default class DetailsScreen extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: [],
};
}
componentDidMount() {
this.setState({
isLoading: false,
dataSource: data.data
});
}
render() {
if (this.state.isLoading) {
return (
<View>
<ActivityIndicator />
</View>
);
}
return (
<View>
<FlatList
data={this.state.dataSource}
renderItem={({ item }) => (this.renderDetailView(item))}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
}
That's the simple rendering of the Flatlist and this work quite good.
The 'renderDetailView' is very complex and long so I couldn't add the code.
But it look like this:
renderDetailView(item) {
return (
<View style={styles.info} key={item.id}>
<View>
<Text style={styles.detailView}>
{item.name}
</Text>
<Text>{'\n'}</Text>
</View>
...
</View>
);
}
At the final project i want to handle a click on an other FlatList and show the detail of the clicked item. the clicked Item 'send' the id to this class and so i get the specific detailView.
Sorry for my bad English.
If you want to navigate to a detail page when you tap an item of your list you should use a navigation library (react-navigation is the most popular).
I created a basic working example :
https://snack.expo.io/#sanjar/so-53747271
(In this example I used react-navigation 2 while the last version is react-navigation 3, so use this one too if you want to reproduce it locally)
ps : I'm not sure to fully understand your requirements, you can add a comment if my answer was off topic or if you have any question

How to call image from JSON that has local path in React Native

import React, { Component } from 'react';
import {
ScrollView,
StyleSheet,
} from 'react-native';
import axios from 'axios';
import CarDetail from '../components/CarDetail';
class CarList extends Component {
state = { cars: [] };
componentDidMount() {
axios.get('https://www.website.com/ajx/home_ajx/lister')
.then(response => this.setState({ cars: response.data.data[0]['S1']
}));
//Add an if statement here to notify the user when the request fails
}
renderCars() {
return this.state.cars.map(model =>
<CarDetail key={model.title} modelprop={model} />
);
}
render() {
console.log(this.state);
return (
<ScrollView>
{this.renderCars()}
</ScrollView>
);
}
}
export default CarList;
And the image path in the JSON file is as below:
"image": "data/models/peugeot-2008-138twf_600X400_.jpg",
Below is where I'm calling the image in another component
const CarDetail = ({ modelprop }) => {
const { image } = modelprop;
return (
<Card>
<CardSection>
<View>
<Image style={imageStyle}
source={{ uri: props.modelprop.image }}
/>
</View>
I believe I need to use some kind of prefix maybe in my Global.js which I couldn't find or figure out.
Any help is highly appreciated.
Mostly like your code has a bug:
const CarDetail = ({ modelprop }) => {
const { image } = modelprop;
return (
<View>
<Image
style={imageStyle}
source={{ uri: image }}
/>
</View>
);
}
If the image is something like data/models/peugeot-2008-138twf_600X400_.jpg, you should use `${Global.imageUrlPrefix}${image}` to concat all.

React-Native: Type Error when parsing JSON

I was trying to implement a News App. It should show a list of news headlines on start with thumbnail image and description and then on clickinh the url should be opened in browser. But, i am stuck on halfway getting a Type Error.
Here are the codes of my NewsList and NewsDetail files.
NewsList.js
import React, { Component } from 'react';
import { ScrollView } from 'react-native';
import axios from 'axios';
import NewsDetail from './NewsDetail';
class NewsList extends Component {
constructor(props) {
super(props);
this.state = {
news: []
};
}
//state = {news: []};
componentWillMount() {
axios.get('https://newsapi.org/v2/top-headlines?country=in&apiKey=MYAPIKEY')
.then(response => this.setState({news: response.data }));
}
renderNews() {
return this.state.news.map(newsData =>
<NewsDetail key={newsData.title} newsData={newsData} />
);
}
render() {
console.log("something",this.state);
return (
<ScrollView>
{this.renderNews()}
</ScrollView>
);
}
}
export default NewsList;
NewsDetail.js
import React from 'react';
import { Text, View, Image, Linking } from 'react-native';
import Card from './Card';
import CardSection from './CardSection';
import Button from './Button';
import NewsList from './NewsList';
const NewsDetail =({ newsData }) => {
const { title, description, thumbnail_image, urlToImage, url } = newsData;
const { thumbnailStyle,
headerContentStyle,
thumbnailContainerStyle,
headerTextStyle,
imageStyle } =styles;
return(
<Card>
<CardSection>
<View>
<Image
style={thumbnailStyle}
source={{uri: urlToImage}}
/>
</View>
<View style={headerContentStyle}>
<Text style={headerTextStyle}>{title}</Text>
<Text>{description}</Text>
</View>
</CardSection>
<CardSection>
<Image
style={imageStyle}
source={{uri:urlToImage}}
/>
</CardSection>
<CardSection>
<Button onPress={() =>Linking.openURL(url)} >
ReadMore
</Button>
</CardSection>
</Card>
);
};
export default NewsDetail;
StackTrace of the Error i am getting
TypeError: this.state.news.map is not a function
This error is located at:
in NewsList (at App.js:11)
in RCTView (at View.js:78)
in View (at App.js:9)
in App (at renderApplication.js:35)
in RCTView (at View.js:78)
in View (at AppContainer.js:102)
in RCTView (at View.js:78)
in View (at AppContainer.js:122)
in AppContainer (at renderApplication.js:34) NewsList.renderNews
NewsList.js:21:31 NewsList.proxiedMethod
createPrototypeProxy.js:44:29 NewsList.render
NewsList.js:31:18 NewsList.proxiedMethod
createPrototypeProxy.js:44:29 finishClassComponent
ReactNativeRenderer-dev.js:8707:30 updateClassComponent
ReactNativeRenderer-dev.js:8674:11 beginWork
ReactNativeRenderer-dev.js:9375:15 performUnitOfWork
ReactNativeRenderer-dev.js:11771:15 workLoop
ReactNativeRenderer-dev.js:11839:25 Object.invokeGuardedCallback
ReactNativeRenderer-dev.js:39:9
App.js
import React from 'react';
import { AppRegistry, View } from 'react-native';
import Header from './header';
import NewsList from './NewsList';
//create component
const App = () => {
return(
<View style={{ flex:0 }}>
<Header headerText={'Headlines'} />
<NewsList />
</View>);
}
export default App;
AppRegistry.registerComponent('news', () => App);
The error you're getting - TypeError: this.state.news.map is not a function, means that news is not an array.
By checking your api response you should do:
this.setState({news: response.data.articles }).
You can actually go to https://newsapi.org/v2/top-headlines?country=in&apiKey="MY_API_KEY" in the browser or use a tool like curl or Postman to check what the response is. The data response is an object, but you need an array. articles is most likely the property you are after.
You may also want to check that this is an array and update what is displayed appropriately.
.then(response => {
const news = response.data.articles;
if (Array.isArray(news)) {
this.setState({ news });
} else {
this.setState({ errorMessage: 'Could not load any articles' });
}
});