How to pass data from a function in react native component - function

I have created a Banner Component in React Native and now im trying to add data from a function (seperate .js file) in this component. I want to fetch the data on the inital load from my Home Screen but i dont know how to pass the data from my function. I hope you can help me.
This is my code:
home.js
export function HomeScreen() {
{/*This will cause an error*/}
const [item, setItem] = React.useState([]);
React.useEffect(() => {
{/*Function where i fetch my Data from API */}
getbannerdata().then(res => {
setItem(res)
})
console.log(item)
}, [])
return (
<SafeAreaProvider>
<SafeAreaView style={style.container}>
<View>
{/*Banner Component with Data param*/}
<Banner data={item} />
<Text>Home</Text>
</View>
</SafeAreaView>
</SafeAreaProvider>
);
}
My function:
bannerdata.js
export const getbannerdata = () => {
const [data, setData] = React.useState([])
console.log('Test')
fetch('http://192.168.178.46:8000/intranet/messages/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then(res => res.json())
.then(res => {
console.log(res)
setData(res)
})
.catch(error => console.log(error));
return data;
};
I hope you can help me.

You should use useState in your component only not in the function where you fetch data.
bannerdata.js
export const getbannerdata = () => {
return fetch('http://192.168.178.46:8000/intranet/messages/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
};
home.js
import { getbannerdata } from './bannerdata'; //import getbannerdata function and you should provide the path of bannerdata.js
export function HomeScreen() {
const [item, setItem] = React.useState([]);
React.useEffect(() => {
{/*Function where i fetch my Data from API */}
getbannerdata()
.then(res => res.json())
.then(res => {
console.log(res)
setItem(res);
});
.catch(error => console.log(error));
}, []);
return (
<SafeAreaProvider>
<SafeAreaView style={style.container}>
<View>
{/*Banner Component with Data param*/}
<Banner data={item} />
<Text>Home</Text>
</View>
</SafeAreaView>
</SafeAreaProvider>
);
}

Thank you for your help.
This is my final solution.
Its a little bit different but now it works as expected
bannerdata.js
import * as React from 'react';
function getbannerdata(){
return fetch ('http://192.168.178.46:8000/intranet/messages/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then((res) => res.json())
.then((resData) => {
return resData;
})
.catch(error => console.log(error))
};
export { getbannerdata }
home.js
import {getbannerdata} from './home/bannerdata.js';
export function HomeScreen() {
const [item, setItem] = React.useState([]);
React.useEffect(() => {
getbannerdata()
.then(res => setItem(res))
}, []);
return (
<SafeAreaProvider>
<SafeAreaView style={style.container}>
<View>
{/*Banner Component with Data param*/}
<Banner data={item} />
<Text>Home</Text>
</View>
</SafeAreaView>
</SafeAreaProvider>
);
}

Related

I can't display the data from an API into a FlatList, but I see it in my console.log. What is the problem?

Console logging my react native app shows the data I fetch from an API. The problem now is that it is not displaying in the FlatList.
const HealthLinkMain = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get(API_URL, {
method: "GET",
headers: {
Authorization: `Bearer ${TOKEN}`,
},
});
setData(response.data)
} catch (error) {
console.error(error);
}
};
fetchData();
}, []);
return (
<View style={styles.container}>
<Text>Test</Text>
<FlatList
data={data.data}
renderItem={(item) => (
<View>
<Text>{item.clinic_name}</Text>
<Text>{item.clinic_address}</Text>
</View>
)}
keyExtractor={(item, index) => item.clinic_name}
/>
</View>
);
};
I think the problem might be in your renderItem as you haven't destructured the item, try this:
renderItem = {({ item }) => {
return (
<View>
<Text>{item.clinic_name}</Text>
<Text>{item.clinic_address}</Text>
</View>
)
}}
You can also seperate it the renderItem into a function of it's own which a lot of people tend to do:
const renderItem = ({item}) => {
return(
<View>
<Text>{item.clinic_name}</Text>
<Text>{item.clinic_address}</Text>
</View>
)
}
and then change the flatlist calling function accordingly:
<FlatList
data={data.data}
renderItem={renderItem}
keyExtractor={(item, index) => item.clinic_name}
/>

Trying to retrive JSON Array through fetch in react native but JSON parse error:Unreconised token "<"

In the code,i am fetching the token from expo-secure-store,later fetching the API data from fetchdata function.But unfortunately error "unrecognized token" is displayed.
After the error is displayed,the API call returns JSON Array data.Unable to do data map in react native to TradeCard Component.
import { StatusBar } from 'expo-status-bar';
import {React,useState,useEffect} from 'react';
import TradeCard from './TradeCard';
import { StyleSheet, Text, View,TextInput,TouchableOpacity,ScrollView,ActivityIndicator } from 'react-native';
import * as SecureStore from 'expo-secure-store';
export default function Trades()
{
const [ data,setData] = useState([]);
const [ isLoading,setLoading] = useState(true);
const [user,setUser] = useState('');
const [token,setToken] = useState('');
const fetchTokens = async () => {
try {
const user = await SecureStore.getItemAsync('user');
const token = await SecureStore.getItemAsync('token');
setUser(user);
setToken(token);
if (user && token)
{
fetchData();
}
else
{
}
} catch (e) {
alert('Error',e);
}
}
useEffect(()=>{ fetchTokens()},[]);
const fetchData = async () => {
setLoading(true);
fetch('https://tradecoaster.herokuapp.com/api/v1/listTrades/'+user+'/',
{
method:'GET',
headers:{
'Accept':'application/json',
'Content-Type':'application/json',
'Authorization':'token '+token
}
})
.then(res => res.json())
.then((res)=>{
console.log('Data',res);
setData(res);
setLoading(false);
})
.catch((error)=>{
setLoading(false);
alert(error);
console.error("Error",error);
});
}
return(
<ScrollView>
<View>
{isLoading && data.length==0 ? <ActivityIndicator size="large" color="#0000ff" /> :
<Text>No Trades</Text>
}
</View>
</ScrollView>
);
}```

React Native fetch API response not displaying

I am creating an app using expo. You can check the snack here
I am also giving the code here:
import React, {Component} from 'react';
import { ActivityIndicator, Text, View, StyleSheet, FlatList, Alert, TouchableOpacity } from 'react-native';
import {Avatar, Card, Button, Divider, ListItem, Image} from 'react-native-elements';
import Icon from 'react-native-vector-icons/FontAwesome';
import Constants from 'expo-constants';
import HTML from 'react-native-render-html';
import UserAvatar from 'react-native-user-avatar';
import { StackNavigator } from 'react-navigation';
import { createAppContainer} from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
class HomeScreen extends React.Component{
static navigationOptions =
{
title: '',
};
constructor(props){
super(props);
this.state = {
Loading : true,
data : []
}
}
fetchLeash(){
fetch('https://lishup.com/app/')
.then((response) => response.json())
.then((responseJson) => {
this.setState({ data: responseJson, Loading:false });
}).catch((error) => {
Alert.alert('error!');
});
}
fetchImage(getimg){
fetch('https://lishup.com/app/fetch-image.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
image: getimg
})
}).then((response) => response.json())
.then((responseJson) => {
return (<Text>responseJson.url</Text>);
}).catch((error) => {
Alert.alert('error');
});
}
componentDidMount(){
this.fetchLeash();
}
renderLeash = ({ item }) => (
<View>
<Card style={{ height:100, justifyContent: 'center', alignItems: 'center' }}>
<ListItem
leftAvatar={{
title: item.user,
source: { uri: item.userpic },
}}
title={item.user}
subtitle={item.time}
chevron
/>
<Divider style={{margin:5, backgroundColor:'white'}} />
<HTML html={item.text} />
{this.fetchImage(item.images)}
</Card>
</View>
)
render(){
if(this.state.Loading == true){
return(
<ActivityIndicator size="large" style={{marginTop:100}} color="#0000ff" />
);
}else{
return(
<View>
<FlatList style={{width:400}}
data={this.state.data}
renderItem={this.renderLeash} />
</View>
);
}
}
}
const styles = StyleSheet.create({
});
const RootStack = createStackNavigator(
{
Home: { screen: HomeScreen },
},
{
initialRouteName: 'Home',
}
);
export default createAppContainer(RootStack);
If you run the snack in your device, you will see that the posts(fetchLeash() function) is working fine. But the fetchImage() is returning nothing.
My fetch-image.php file is here:
<?php
// Importing DBConfig.php file.
include 'DB.php';
header('Content-Type: application/json');
// Creating connection.
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
// Getting the received JSON into $json variable.
$json = file_get_contents('php://input');
// decoding the received JSON and store into $obj variable.
$obj = json_decode($json,true);
// Populate User email from JSON $obj array and store into $email.
$image = $obj['image'];
if($image == "") {
$blank[] = array("url"=>"");
echo json_encode($blank);
}else{
//query to get image url with the code received
$Sql_Query = "SELECT * FROM `leash_img` WHERE `pid`= '".$image."' ";
// Executing SQL Query.
$check = mysqli_query($con,$Sql_Query);
if($check){
while($row=mysqli_fetch_assoc($check)){
$SuccessLoginMsg[] = array("url"=> $row['image']);
}
// Converting the message into JSON format.
$SuccessLoginJson = json_encode($SuccessLoginMsg);
echo $SuccessLoginJson;
}
}
?>
This returns like the following:
[{"url":"link here"}]
The PHP file is working fine. But the react native fetchImage() is not working.
I am totally new to react native. So forgive my problems. I am just out of my ideas. Please help me.
You can't asynchronously render UI from the render function, you need to fetch the data outside it in one of the lifecycle functions and conditionally render UI while it is being fetched.
Once the data has been fetched you should go ahead and fetch the image urls. Use Promise.all and map each response item to a fetch request. This will allow all image url fetches to resolve asynchronously and maintain index order.
fetchLeash() {
fetch('https://lishup.com/app/')
.then((response) => response.json())
.then((responseJson) => {
this.setState({ data: responseJson });
Promise.all(responseJson.map(({ images }) => this.fetchImage(images)))
.then((images) => {
this.setState({ imageUrls: images.map(url => ({ uri: url })) })
});
})
.catch((error) => {
Alert.alert('error!');
})
.finally(() => {
this.setState({ Loading: false });
});
}
The other important change is that the image response is an array of length 1, so need to access correctly.
fetchImage(image) {
return fetch('https://lishup.com/app/fetch-image.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ image }),
})
.then((response) => response.json())
.then((responseJson) => responseJson[0].url);
}
Now you can conditionally render an Image if the url at that index exists.
renderLeash = ({ item, index }) => (
<View>
<Card
style={{ height: 100, justifyContent: 'center', alignItems: 'center' }}>
<ListItem
leftAvatar={{
title: item.user,
source: { uri: item.userpic },
}}
title={item.user}
subtitle={item.time}
chevron
/>
<Divider style={{ margin: 5, backgroundColor: 'white' }} />
<HTML html={item.text} />
<Text>
{this.state.imageUrls[index] && this.state.imageUrls[index].uri}
</Text>
{this.state.imageUrls[index] && (
<Image
source={this.state.imageUrls[index]}
style={{ width: 100, height: 100 }}
PlaceholderContent={<ActivityIndicator />}
/>
)}
</Card>
</View>
);
Expo Snack
EDIT Allow display of all fetched image URLs. Instead of grabbing and returning just the first URL, return an array of URLs. Below I mapped the URLs to a new array before returning them, and these can be set directly in state now. Update the render function to use an additional guard (array length check) and render null if array doesn't exist. (Could also use another FlatList here if you wanted to)
fetchLeash() {
return fetch('https://lishup.com/app/')
.then((response) => response.json())
.then((responseJson) => {
this.setState({ data: responseJson });
Promise.all(
responseJson.map(({ images }) => this.fetchImage(images))
).then((imageUrls) => this.setState({ imageUrls }));
})
.catch((error) => {
Alert.alert('error!');
})
.finally(() => {
this.setState({ Loading: false });
});
}
fetchImage(image) {
return fetch('https://lishup.com/app/fetch-image.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ image }),
})
.then((response) => response.json())
.then((responseJson) =>
// Filter elements with empty string URLs, then app just the URL
responseJson.filter(({ url }) => url).map(({ url }) => url)
);
}
...
{this.state.imageUrls[index] && this.state.imageUrls[index].length
? this.state.imageUrls[index].map((uri) => (
<Image
source={{ uri }}
style={{ width: 100, height: 100 }}
PlaceholderContent={<ActivityIndicator />}
/>
))
: null}

Trouble display name property from axios fetched json object

https://codesandbox.io/s/currying-voice-toq9t - I am trying to save the json object into the component state, then render the name into the browser.
getProfile() {
axios
.get(
"https://cors-anywhere.herokuapp.com/" +
"https://phantombuster.s3.amazonaws.com....."
)
.then(response => {
this.setState({
profile: {
name: response.data.name
}
});
})
.catch(error => this.setState({ error, isLoading: false }));
}
Your Response data is an array form so,You need to give Index.I hope it will helps you.
getProfile() {
axios
.get(
"https://cors-anywhere.herokuapp.com/" +
"https://phantombuster.s3.amazonaws.com/YRrbtT9qhg0/NISgcRm5hpqtvPF8I0tLkQ/result.json"
)
.then(response => {
this.setState({
profile: {
name: response.data[0].name
}
});
})
.catch(error => this.setState({ error, isLoading: false }));
}
The response.data is an array where in first position there is the information that you are looking for, so the setState should be like this:
this.setState({
profile: {
name: response.data[0].name
}
});
or
const [obj] = response.data;
this.setState({
profile: {
name: obj.name
}
});
Your response.data returns an array.so you need to traverse it inside a loop.
import React from "react";
import ReactDOM from "react-dom";
import axios from "axios";
export class Profile extends React.Component {
constructor(props) {
super(props);
this.state = { profile: [] };
}
componentDidMount() {
this.getProfile();
}
getProfile() {
axios
.get(
"https://cors-anywhere.herokuapp.com/" +
"https://phantombuster.s3.amazonaws.com/YRrbtT9qhg0/NISgcRm5hpqtvPF8I0tLkQ/result.json"
)
.then(response => {
console.log("response: ", response)
this.setState({
profile: response.data
});
})
.catch(error => this.setState({ error, isLoading: false }));
}
render() {
let { name } = this.state.profile;
const { error } = this.state;
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Profile</h1>
{error ? <p>{error.message}</p> : null}
</header>
<div className="App-feeds" />
<div className="panel-list">
{this.state.profile.map((element) => <p>First Name: {element.name}</p>)}
</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Profile />, rootElement);

Parsing JSON with react native, looping through

i am trying to parse a json file by displaying all the names in the clubs
the json file is https://raw.githubusercontent.com/openfootball/football.json/master/2017-18/it.1.clubs.json
my current code i have is
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: null,
}
}
componentDidMount() {
return fetch('https://raw.githubusercontent.com/openfootball/football.json/master/2017-18/it.1.clubs.json')
.then ( (response) => response.json() )
.then ( (responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.clubs,
})
})
.catch((error) => {
console.log(error)
});
}
render() {
if (this.state.isLoading) {
return (
<View style = {styles.containter}>
<ActivityIndicator/>
</View>
)
} else {
return (
<View>
<Text>{this.state.dataSource.name}</Text>
</View>
)
I just want to loop through to display all the names in the clubs
Try this:
Couple of edits: Changing the initial state of dataSouce value as an array, this is to ensure it doesn't throw can't read property map of undefined.
You don't need to return the fetch call, because you don't need a promise to returned.
EDIT: Added a loading text before all the clubs are loaded.
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
state = {
isLoading: false,
dataSource: []
};
componentDidMount() {
this.setState({ isLoading: true }, () => {
fetch(
"https://raw.githubusercontent.com/openfootball/football.json/master/2017-18/it.1.clubs.json"
)
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
this.setState({
isLoading: false,
dataSource: responseJson.clubs
});
})
.catch(error => {
this.setState({ loading: false });
console.log(error);
});
});
}
render() {
return (
<div className="App">
<h1>Club Names</h1>
{this.state.isLoading ? (
<h1>Loading Clubs...</h1>
) : (
this.state.dataSource.map(data => <h2 key={data.key}>{data.name}</h2>)
)}
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Sandbox Link: https://codesandbox.io/s/throbbing-dream-7lpcm?fontsize=14