I would like to know how I can view data from my fetch query in my app.
I have a node that is fetched from React native and I want to display the response.
The node part;
app.get('/balance', function(req, res){
//calling the function
res.jsonp('0');
console.log("CRYPTO CALLED");
});
The react function;
_getBalanceFromApiAsync() {
fetch('http://192.168.1.100:3000/ballance')
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
return responseJson;
})
.catch((error) => {
console.error(error);
});
}
I can see the result in the node console as well as the react console. But where it doesn't work is here.
Native app;
<Text style={styles.getStartedText}>Your Wallet Balance</Text>
<Text> {this._getBalanceFromApiAsync()}</Text>
</View>
The function is getting executed but I would like to display the returned value and as it is the text field remain empty
Thank you
Its simple you need to setState for re-rendering the component. Try doing this
constructor(props){
super(props)
this.state = {
textData: ''
}
}
componentDidMount(){
this.getBalanceFromApiAsync()
}
getBalanceFromApiAsync() {
fetch('http://192.168.1.100:3000/ballance')
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
this.setState({
textData: responseJson
})
})
.catch((error) => {
console.error(error);
});
}
<Text style={styles.getStartedText}>Your Wallet Balance</Text>
<Text> {this.state.textData}</Text>
</View>
Related
I am trying to display data that I fetched with Axios. They came as an array. Because of this I cant show them. What should I do?
Here is my fetch code
componentDidMount() {
axios.post('http://192.168.1.106:80/partner_project_backend/project_list.php')
.then((response) => {
console.log(response.data)
})
.catch((error) => {
console.error(error);
});
}
Here is my console.log
I'm guessing you are getting the API response correctly and your only intention is to display the data in your application. If so, you could use the FlatList component from React Native
import React from 'react';
import { FlatList, Text } from 'react-native';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
};
}
componentDidMount() {
axios.get('http://192.168.1.106:80/partner_project_backend/project_list.php')
.then((response) => {
this.setState({ data: response.data });
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<FlatList
data={data}
renderItem={({ item }) => (
<Text>{item.name}</Text> // render your view here
)}
keyExtractor={item => item.id}
/>
);
}
}
React more about FlatList at https://reactnative.dev/docs/flatlist
To fetch data you have to use get method NOT post
this.state ={ data : null }
componentDidMount(){
axios.get('http://192.168.1.106:80/partner_project_backend/project_list.php')
.then((response) => {
this.setState({ data : response.data })
})
.catch((error) => {
console.error(error);
});
}
I'm trying to use react-native-rss-parser (https://www.npmjs.com/package/react-native-rss-parser) to parse my RSS feed and display it on a card but I don't know how to access the rss variable.
fetchRSSFeed() {
return fetch('http://www.nasa.gov/rss/dyn/breaking_news.rss')
.then((response) => response.text())
.then((responseData) => rssParser.parse(responseData))
.then((rss) => { console.log(rss.title) })
}
render() {
{this.fetchRSSFeed()}
return (
<SafeAreaView style={styles.container}>
<Swiper
cards={HomeScreenPics}
renderCard={Card}
infinite
backgroundColor="white"
cardHorizontalMargin={0}
stackSize={2}
/>
</SafeAreaView>
)
}
}
HomeScreenPics = [{
pic: require('../assets/images/news.jpg'),
title: rss.title
}]
console.log(rss.title) works fine. It logs out the RSS feed title but I'm trying to access the rss varible outside the fetch method, I want to parse it into my HomeScreenPics array, but it keeps showing the error: Can't find variable rss
If you want to access the rss variable and pass it to the render function, all you have to do is to use the state that react provides you.
Example:
state = {
feed: {}
}
fetchRSSFeed() {
return fetch('http://www.nasa.gov/rss/dyn/breaking_news.rss')
.then((response) => response.text())
.then((responseData) => rssParser.parse(responseData))
.then((rss) => {
this.setState(prevState => ({
...prevState,
feed: rss
}));
})
}
render() {
{this.fetchRSSFeed()}
return (
<SafeAreaView style={styles.container}>
<Swiper
cards={HomeScreenPics}
renderCard={Card}
infinite
backgroundColor="white"
cardHorizontalMargin={0}
stackSize={2}
/>
<Text>{this.state.feed.title}</Text>
</SafeAreaView>
)
}
}
You can access the response object with the variable this.state.feedin any function.
I recommend you to start from the official documentation: [https://facebook.github.io/react-native/docs/state]
Friendly.
I am actually facing the same issue as you had. xarhsasi answers works like a charm.
Bear in mind that you can avoid calling the function each time since you are willing to render it once, just at the beginning.
I strongly recommend you to add it into a componentDidMount(), like so
constructor(props) {
super(props);
this.state = {
isLoading: true,
feed: {}
}
}
componentDidMount() {
return fetch('http://www.nasa.gov/rss/dyn/breaking_news.rss')
.then((response) => response.text())
.then((responseData) => rssParser.parse(responseData))
.then((rss) => {
this.setState({
isLoading: false,
feed: rss
});
});
}
Then, you only need to call the state like xarhsasi told you with this.state.feed.title, for example.
Best regards,
**I am using REACT NATÄ°VE for a project. I need to integrate the website and the mobile application. I have to use WooCommerce Rest API for that. I'm trying to learn but I can't see the data I want to capture. I can not see anything.
**
import WooCommerceAPI from 'react-native-woocommerce-api';
const WooCommerce = new WooCommerceAPI({
url: 'http://myurl', // Your store URL
ssl: true,
consumerKey: '****************',
consumerSecret: '***************',
wpAPI: true, // Enable the WP REST API integration
version: 'v3', // WooCommerce WP REST API version
queryStringAuth: true
});
WooCommerce Config
class X extends Component{
constructor(props) {
super(props);
}
componentWillMount() {
// GET example
return(
WooCommerce.get('products') .then(response => response.json())
.then(responseJson => {
this.setState(prevState => ({
products: [...prevState.products, ...responseJson],
isLoading: false
}));
})
.catch(error => {
console.error(error);
}))
}
<FlatList
data={this.state.products}
renderItem={({item}) => <View>
<Text>{item.name}</Text>
<Text>{WooCommerce.get('products').id}</Text>
</View>}
keyExtractor={item => item.id.toString()}
/>
Data is not fetching, i dont see anything, what is a problem ?
I know my answer might be coming late but for those who are having the same issue. You don't need to add the first then with response.json(). Please look at examples here https://www.npmjs.com/package/react-native-woocommerce-api
componentWillMount() {
// GET example
return(
WooCommerce.get('products')
.then(responseJson => {
this.setState(prevState => ({
products: [...prevState.products, ...responseJson],
isLoading: false
}));
})
.catch(error => {
console.error(error);
}))
}
i try fetch info from server and while fetching not complete show searching Component and when fetch done show information...everything is OK...But when NET offline show searching component and when turning on NET i want show a button "Try Again" and when click on "FetchData" function run again.
constructor(){
super();
this.state={
isLoading:true,
dataSource:null,
dataError:false
}
}
componentDidMount(){
FetchData = () => {
return fetch(SuperUrl+'/info')
.then((response)=>response.json())
.then((responseJson)=>{
this.setState({
isLoading:false,
dataSource: responseJson
})
})
.catch((error)=>{this.setState({dataError:true})})
}
FetchData()
}
render() {
if(this.state.dataError)
{
<View>
<Buttom onpress={()=>{FetchData()}}>
<Text>Try Again</Text>
<Button>
</View>
}
if(this.state.isLoading)
{
return(
<Container>
<StatusBar backgroundColor={'#3949ab'}/>
<Searching/>
<JaFooter list={{backgroundColor:'#3949ab', color:'#ffffff'}}/>
</Container>
)
}
else
{
let regionName = this.state.dataSource.map((value,key)=>{
return(
<ListItem key={key} >
<Text key={key} style={styles.cityName}>{value.name}</Text>
</ListItem>
)
})
Your title is very misleading as componentDidMount should run once. What you want is totally different so I'll explain. Since you are asking for something that goes against the pattern of RN you are risking getting your answer closed. Anyway..
Fetch does not support a timeout natively. But you can workaround it by running two promises. One for your fetch, and another for the timeout. This is pseudo code, you are gonna have to learn about Promise.race and how setTimeout works.
const promise1 = fetch;
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => reject(new TimeoutError()), 30000);
})
Promise.race([promise1, promise2])
.then(() => {
//You got a response from the server
})
.catch(err => {
//Probably timeout
if (err.code == 'Timeout')
this.setState({loading: false, showTryAgain: true})
})
Promise.race will run both in parallel but if the network request for the fetch ends first, it will ignore the timeout which is what you want.
I'm an Android developer, but am new to JavaScript or react-native. I was following Facebook's react-native tutorial and I was able to copy-paste its sample code into my index.android.js and click 'R-R' key to see the resulting UI in my simulator, until this network section. The code sample does not show how fetch is hooked up with render(), therefore is just an excerpt and no longer compilable. I tried to put it within render(){return like below code, but it throws error
myFetch.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
class myFetch extends Component{
render(){
return (
fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
})
);
};
}
AppRegistry.registerComponent('HelloWorldApp', () => myFetch);
How to fix it in the simplest way, and what are the pointers to read, please?
class myFetch extends Component{
constructor(props){
super(props);
this.state = {movies: 'init'};
}
componentDidMount() {
fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {this.setState({movies: responseJson.title});})
.catch((error) => {
console.error(error);
})
}
render(){
return (
<Text>{this.state.movies}</Text>
);
}
}
AppRegistry.registerComponent('HelloWorldApp', () => myFetch);
The render() method must return a React element (or null) like <View></View>.
And the network request should implement in componentDidMount() or other Lifecycle method.