I'm really rusty with my react-native, haven't touched it in like 4 years.
I am trying to extract a cryptocurrency price from a publicly available API (as shown in the code below). i think I got the price but packing that value into something that's usable is proving to be difficult. What am i doing wrong? Either I haven't set up the const correctly or something else is going on.
import React, {Component, useState, useEffect} from 'react';
import {AppRegistry, StyleSheet, Text, View} from 'react-native';
const getPriceFromApi = () => {
//GET request
fetch('https://api.coingecko.com/api/v3/simple/price?ids=bone-shibaswap&vs_currencies=usd', {
method: 'GET',
})
.then((response) => response.json())
//If response is json then in success
.then((responseJson) => {
//Success
return responseJson;
})
}
const App = () => {
const [price, setPrice] = useState([]);
useEffect(() => {
const fetchPrice = async () => {
const data = await getPriceFromApi();
setPrice(data);
// this should produce ONE value and one value only.
// however it’s throwing an error, grrrrr.
}
}, [getPriceFromApi])
return ();
type Props = {};
export default class MyApp extends Component<Props> {
render() {
return (
<View style={styles.container}>
<Text style={styles.bone}>
🍖
</Text>
<Text style={styles.welcome}>
you have > 120.00
</Text>
<Text style={styles.instructions}>
the value of bone is:
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#2A2734',
},
bone: {
fontSize: 64,
textAlign: 'center',
margin: 10,
color: 'red'
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
color: 'white'
},
instructions: {
textAlign: 'center',
color: '#B0B0B0',
marginBottom: 5,
},
});
// You must register the main component
// with the same name as the project
AppRegistry.registerComponent(
'bone-price', () => MyApp
);
If you are writing a another function for fetching data from API, you may forget to return the value by fetch. It will always return undefined.
You should modify the function getPriceFromApi().
const getPriceFromApi = () => {
//This return is for function - getPriceFromApi()
return fetch('https://api.coingecko.com/api/v3/simple/price?ids=bone-shibaswap&vs_currencies=usd', {
method: 'GET',
})
.then((response) => response.json())
.then((responseJson) => {
//This return is for function - fetch()
return responseJson;
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.