FlatList - Fetching Data From Postman Localhost url - javascript

Hi Everyone,
I'm very beginner to this platform.
Could any one help me to where i did mistake in the following code?
i'm Using SQL server for database
In App.js I have tried the below code...
import React, { Component } from 'react';
import {
StyleSheet,
View,
ActivityIndicator,
TouchableOpacity,
Text,
Dimensions,
FlatList
} from 'react-native';
export default class App extends React.Component {
//Set States
constructor(props)
{
super(props);
this.state={
isLoading: true,
dataSource: []
}
}
//Get Data From API
componentDidMount()
{
fetch('http://localhost:7483/api/StudentData/')
.then((response)=>response.json())
.then((responseJson)=>{
this.state({
isLoading: false,
dataSource: responseJson
})
})
}
_renderItem=({item,index}) => {
return(
<View>
<Text>Hello</Text>
</View>
);
}
render()
{
let {container}=styles
let {dataSource,isLoading}=this.state
//Use FlatList for Display Data
return(
<View style={container}>
<FlatList
data={dataSource}
renderItem={this._renderItem}
keyExtractor={(item,index) => index.toString()}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
alignItems:'center'
},
welcome:{
fontSize:20,
textAlign:'center',
margin:10
}
});
I'm getting data in postman url from SQL server
I'm getting this warning msg
Empty Emulator Screen
Console Warning msg

In the android emulator URL with localhost not working, so you must set ipv4 address instead of that.
Also change this.state -> this.setState

Add you IP address instead of localhost
1.) Run cmd
2.) type ipconfig
3.) Scroll Down to IPv4 Address. . . . . . . . . . . : 192.168.**.**
4.) Copy this IP and replace it in place of localhost
5.) Done
Get your IP like this
So Suppose if your IPv4 address is - 192.168.100.84 then
Your fetch should look like this
fetch('http://192.168.100.84:7483/api/StudentData/')
Also for setting state after fetch
You have to do like this
this.setState({ isLoading: false, dataSource: responseJson })
Instead of this
this.state({ isLoading: false, dataSource: responseJson })
In your render part write like this
return(
<View style={styles.container}>
<FlatList
data={this.state.dataSource}
renderItem={this._renderItem}
keyExtractor={(item,index) => index.toString()}
/>
</View>
);
Your App.js using Function Component
import React, { Component, useState, useEffect } from 'react';
import {
StyleSheet,
View,
ActivityIndicator,
TouchableOpacity,
Text,
Dimensions,
FlatList,
} from 'react-native';
export default function App() {
const [State, setState] = useState({
loading: true,
dataSource: [],
});
useEffect(() => {
GetData();
}, []);
const GetData = async () => {
const result = await fetch('http://192.168.43.159:7483/api/StudentData/');
const response = await result.json();
setState({
...State,
isLoading: false,
dataSource: response,
});
};
const _renderItem = ({ item, index }) => {
return (
<View>
<Text>Hello</Text>
</View>
);
};
return (
<View style={styles.container}>
<FlatList
data={State.dataSource}
renderItem={_renderItem}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
});

Related

ScrollView in React Native

I created a simple app, that shows a few pictures with titles. It is something like a film gallery, where you can observe all enable films. But when I try to add ScrollView element it doesn't work when I try to scroll on my emulated Android device. How can I fix it? My code looks like this:
import React, { Component } from 'react'
import { View, ScrollView, StyleSheet } from 'react-native'
import { Header, ImageCard } from './src/components/uikit'
const url = 'https://s3.eu-central-1.wasabisys.com/ghashtag/RNForKids/00-Init/data.json'
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
title: 'STAR GATE',
data: []
};
}
componentDidMount = async () => {
try {
const response = await fetch(url)
const data = await response.json()
this.setState({ data })
}
catch (e) {
console.log(e)
throw e
}
}
render() {
const { title, data } = this.state
const { container } = style
return (
<View>
<Header title={title} />
<ScrollView>
<View style={container}>
{
data.map(item => {
return <ImageCard data={item} key={item.id} />
})
}
</View>
</ScrollView>
</View>
)
}
}
const style = StyleSheet.create({
container: {
marginTop: 30,
flexDirection: 'row',
flexWrap: 'wrap',
flexShrink: 2,
justifyContent: 'space-around',
marginBottom: 150
}
})
I made it with a guide, so it should work. (Youtubes author hasn't this problem on his video).
The View inside ScrollView looks problematic. Try something like:
<ScrollView contentContainerStyle={container} >
{
data.map(item => {
return <ImageCard data={item} key={item.id} />
})
}
</ScrollView>

how to access particular data in api call response in react native

I am using react native and working with the moviesDB API.For some reason, I cannot access the data I am looking for in the response of the api call. I am trying to get the "poster_path" info from the api call. So in my console.log, If call this.state.movies, I see the data of many movies there as well as the "poster_path" key that I want to access and its info. However, when I console.log this.state.movies.poster_path, it shows undefined. Just wondering why its doing that. I have tried searching online for answers and also tried to wrap brackets and take out the spread operator. Please see below for code and picture of console. Thanks!
import { View, Text, StyleSheet, TextInput, Image } from "react-native";
import { FlatList, TouchableOpacity } from "react-native-gesture-handler";
import MovieItem from "../components/MovieItem";
const API_KEY2="*******";
class SearchScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
movies: \[\],
searchTerm: "",
}
}
handleSubmit =(e)=> {
fetch(`https://api.themoviedb.org/3/search/movie?api_key=${API_KEY2}&query=${this.state.searchTerm}`)
.then(data => data.json())
.then(data=> {
this.setState({
movies: \[...data.results\]
});
console.log("RESPONSE FROM THIS.STATE.MOVIES", this.state.movies)
console.log("RESPONSE FROM THIS.STATE.MOVIES.POSTER_PATH",this.state.movies.poster_path)
})
}
handleChange=(textToSearch)=> {
this.setState({
searchTerm: textToSearch
});
}
render() {
return(
<View style={styles.screen}>
<TextInput
style={styles.input}
onSubmitEditing={this.handleSubmit}
onChangeText={(text)=>this.handleChange(text)}
placeholder="Enter Movie"
/>
<FlatList
data={this.state.movies}
renderItem={({item})=> {
return(
<TouchableOpacity onPress={()=> this.props.navigation.navigate("MovieItem", {item})}>
<View style={styles.movieItem}>
<Image source={{uri:`https://image.tmdb.org/t/p/w1280/${item.poster_path}`}}
style={{
height: 220,
width: 200
}}/>
<MovieItem item={item}/>
</View>
</TouchableOpacity>
)
}} />
</View>
)
}
}
const styles = StyleSheet.create({
screen: {
flex: 1,
backgroundColor:"tomato",
justifyContent:"center",
alignItems:"center",
flexDirection:"column"
},
input: {
borderStyle:"solid",
borderWidth: 5,
width:"100%",
padding: 20,
backgroundColor:"white",
fontFamily:"Yesteryear-Regular",
fontSize: 20,
color:"tomato"
},
movieItem: {
marginTop: 20,
marginBottom: 20
},
})
export default SearchScreen;][1]][1]
// response for this.state.movies
// response for this.state.movies.poster_path
var temp = [{'poster_path' :'xxx'}];
temp[0].poster_path;

React native - Invariant violation-tried to get frame for out of range index

I have tried to search other posts and forums for the solution to this error. However, either no one has solved those issues or the issues are not really doing the same thing as I am doing. I am getting an error saying " Invariant violation-tried to get frame for out of range index". This happens when I try to input the data into the flatlist from the poke api. Please see code below.
import React, { useState } from "react";
import { View, Text , Button, FlatList, ActivityIndicator } from "react-native";
import { GlobalStyles } from "../styles/GlobalStyles";
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: []
}
}
componentDidMount() {
fetch("https://pokeapi.co/api/v2/pokemon/")
.then((res)=> res.json())
.then((response)=> {
this.setState({
isLoading: false,
dataSource: response
})
console.log(response)
})
}
render() {
const showIndicator = this.state.isLoading == true ? <ActivityIndicator size="large" color="#0000ff" /> : null;
return(
<View style={GlobalStyles.container}>
<View style={GlobalStyles.activityIndicator}>{showIndicator}</View>
<FlatList data={this.state.dataSource} renderItem={({item})=> {
return(
<View>
<Text>{item.name}</Text>
</View>
)
}}/>
<Button onPress={()=> this.props.navigation.navigate("About")} title="Go to about"/>
</View>
)
}
}
export default Home;
The thing you are doing wrong is you are sending this.state.datasource is your data attribute, you need to send this.state.dataSource.results
import React, { useState } from "react";
import { View, Text , Button, FlatList, ActivityIndicator } from "react-native";
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: []
}
}
componentDidMount() {
fetch("https://pokeapi.co/api/v2/pokemon/")
.then((res)=> res.json())
.then((response)=> {
this.setState({
isLoading: false,
dataSource: response
})
console.log(response)
})
}
render() {
const showIndicator = this.state.isLoading == true ? <ActivityIndicator size="large" color="#0000ff" /> : null;
return(
<View style={{marginTop:100}}>
<View>{showIndicator}</View>
<FlatList data={this.state.dataSource.results}
renderItem={({item})=> {
console.log("item is item",item);
return(
<View>
<Text>{item.name}</Text>
</View>
)
}}/>
<Button onPress={()=> this.props.navigation.navigate("About")} title="Go to about"/>
</View>
)
}
}
export default Home;
Hope this helps!

AsyncStorage data not displayed in FlatList

I create an application that retrieves data from a URL (an array of objects) and display it in FlatList. I'm a beginner and therefore I don't use Redux or other for the moment. I would like to store my data in AsyncStorage and display them.
I tried this, but my data are not displayed int FlatList:
import React, {Component} from 'react';
import {ScrollView, View, FlatList, Image, ActivityIndicator, AsyncStorage} from 'react-native';
import axios from "axios";
import {ListItem} from "react-native-elements";
import {createAppContainer, createStackNavigator} from "react-navigation";
import AppConfig from "../../AppConfig";
import Keys from "../../data/Constants/Storage";
import PronosticsDetailsScreen from "../../screens/PronosticsDetailsScreen";
class MontanteTab extends Component {
state = {
errors: null,
isLoading: true,
pronostics: [],
};
async componentDidMount() {
const isConnected = true;
if (isConnected) {
await this.loadPronostics();
}
try {
this.setState({pronostics: JSON.parse(await AsyncStorage.getItem(Keys.pronosticsMontante))});
} catch (error) {
console.log(error);
}
}
loadPronostics() {
this.setState({isLoading: true, error: null});
return axios.get(AppConfig.apiUrl + 'montante').then(async response => {
await AsyncStorage.setItem(Keys.pronosticsMontante, JSON.stringify(this.state.pronostics));
this.setState({isLoading: false});
}).catch(error => {
this.setState({isLoading: false, error: error.response});
console.log(error);
});
}
render() {
if (this.state.isLoading === true) {
return (
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return (
<View>
<ScrollView>
<View>
<FlatList
data={this.state.pronostics}
extraData={this.state.pronostics}
keyExtractor={(item, index) => index.toString()}
renderItem={({item}) => (
<ListItem
key={item.id}
roundAvatar
badge={{
value: item.statut,
textStyle: {color: '#fff'},
containerStyle: {marginRight: 0, backgroundColor: item.couleur}
}}
avatar={<Image
source={{uri: AppConfig.imagesPronosticsUrl + item.image}}
style={{borderRadius: 50, height: 50, width: 50}}/>}
title={item.competition}
subtitle={item.equipe_domicile + ' - ' + item.equipe_exterieur}
onPress={() => this.props.navigation.navigate('PronosticsDetails', {
item,
})}
/>
)}
/>
</View>
</ScrollView>
</View>
);
}
}
What's the problem please ?
I'm not an expert here, but...
One "odd" thing about FlatLists is that they are Pure Components so they don't always rerender when you expect. FlatList helps you out here and provides a property called extraData. You can use this to tell FlatList what to watch to know if there is an important change. So, try adding:
extraData={ this.state.pronostics }
to your FlatList.
The problem is solved.
I replaced :
await AsyncStorage.setItem(Keys.pronosticsMontante, JSON.stringify(this.state.pronostics));
by :
await AsyncStorage.setItem(Keys.pronosticsMontante, JSON.stringify(response.data));

What's the reason for the error being thrown on init() method?

I used https://www.npmjs.com/package/react-native-dynamodb to implement DynamoDB access for my project. I used the same exact code as that website.
The only thing is, I can't see how my .init() method is giving me: Unresolved function or method init() upon hovering over it (I'm using the WebStorm IDE by the way). I believe that's the reason why my app won't run. Below is the code as well as the error I'm getting in the simulator.
Error in iOS Simulator
Here's my .js file:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ScrollView, Text, View, Button } from 'react-native';
import { logout } from '../redux/actions/auth';
import DropdownMenu from 'react-native-dropdown-menu';
import Icon from './Icon';
import DynamoDB from 'react-native-dynamodb';
let dynamodb = DynamoDB.init({
credentials: {
AccessKeyId: 'Some key',
SecretKey: 'Some key'
}
// region: 'us-east-1' - default, optional
// version: '20120810' - default, optional
})
dynamodb.table('user_choice').PutItem(
{
name: 'Jack Sparrow',
age: 30,
captain: true
},
{
ConditionExpression: "last_movie <> :movie",
ExpressionAttributeValues: {
":movie": {"S": "Pirates of the Caribbean: On Stranger Tides"}
}
})
.then((response) => console.log(response)) // AWS object response
.catch((error) => {
console.log(error)
})
class Secured extends Component {
render() {
var data = [["Literacy Leaders"], ["Wrestling Camp"], ["Screenplay Writing"], ["Panetarium Workshop"]];
return(
<ScrollView style={{padding: 20}}>
<Icon/>
<Text style={{fontSize: 27}}>
{`Welcome ${this.props.username}`}
</Text>
<View style={{flex: 1}}>
<DropdownMenu style={{flex: 1}}
bgColor={"purple"} //the background color of the head, default is grey
tintColor={"white"} //the text color of the head, default is white
selectItemColor={"orange"} //the text color of the selected item, default is red
data={data}
maxHeight={410} // the max height of the menu
handler={(selection, row) => alert(data[selection][row])} >
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}} >
</View>
</DropdownMenu>
</View>
<View style={{margin: 20}}/>
<Button onPress={(e) => this.userLogout(e)} title="Logout"/>
</ScrollView>
);
}
}
const mapStateToProps = (state, ownProps) => {
return {
username: state.auth.username
};
}
const mapDispatchToProps = (dispatch) => {
return {
onLogout: () => { dispatch(logout()); }
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Secured);
I checked the source code of react-native-dynamodb, seems DynamoDB is not exported as default but a named export.
Try import it like this:
import { DynamoDB } from 'react-native-dynamodb';

Categories

Resources