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);
});
}
Related
I have following code.
axios.post('/user', {
limit: '1000',
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
It took around 1-3 seconds to get data. In the meantime, how can I display something like loading..... or fetching.....
if you are working with classes in react native then you can use the below implementation, let me know if you are facing any issues.
import {ActivityIndicator } from 'react-native';
export class YOUR_CLASS_NAME extends Component{
constructor(props)
{
super(props);
this.state ={
isFetching:false,
}
}
async componentDidMount()
{
this.setState({isFetching:true});
//fetch your data here from axios
this.setState({isFetching:false});
}
render()
{
return(
<View style={{flex:1}}>
//your text
{this.state.isFetching &&
<ActivityIndicator animating={true} backgroundColor="#ffffff" color={'#000000'} />
}
</View>
);
}
}
take a state
const [loading, setLoading] = useState(false)
now in your code before the axios call
setLoading(true)
axios.post('/user', {
limit: '1000',
})
.then(function (response) {
console.log(response);
setLoading(false)
})
.catch(function (error) {
console.log(error);
setLoading(false)
});
now you can display an activity indicator or whatever you want to display when the data is loaded by checking the loading state in your code
{loading && <Text>loading...</Text>}
or
{loading && <ActivityIndicator animating />}
Hi this is my code in App.js
var music = {
name: "Starboy",
artist: "The Weeknd",
albumArt: "",
length: "4:20",
audioURL:"",
};
export default class App extends Component
{
render() {
return (
<Image style={styles.albumArt} source={{ uri:music.albumArt }} />
);
}
};
I have another function in lastFM.js
export function getAlbumArt(albumName)
{
fetch('http://ws.audioscrobbler.com/2.0/?method=album.search&album='+albumName+'&api_key=MY_API_KEY&format=json&limit=1')
.then((response) => response.json())
.then((result) => {
const image = result.results.albummatches.album[0].image[2]['#text'];
console.log(image);
return image;
})
.catch((error) => {
console.log("ERROR: "+error);
});
}
How can I update music.albumArt in App.js and re-render Image inside App.js Render?
This might help. Re-render happens when you change the state of the component. So, here we are updating the state once we get data from the API.
export default class App extends React.Component {
constructor() {
super();
this.state = {
name: "Starboy",
artist: "The Weeknd",
albumArt: "",
length: "4:20",
audioURL: ""
};
}
componentDidMount(){
fetch('http://ws.audioscrobbler.com/2.0/?method=album.search&album='+albumName+'&api_key=MY_API_KEY&format=json&limit=1')
.then((response) => response.json())
.then((result) => {
const image = result.results.albummatches.album[0].image[2]['#text'];
console.log(image);
this.setState({...this.state, albumArt: image });
})
.catch((error) => {
console.log("ERROR: "+error);
});
}
render() {
return <Image style={styles.albumArt} source={{ uri: this.state.albumArt }} />;
}
}
I am using Zomato API to get the list of restaurants, data is in the form of the array which has object restaurants in which there are different restaurant objects and then their name and other details.
It's my first time using a flat List and I am not able to display this data.
Goal: Use the search bar to display the list of restaurants in the city using flatlist.
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { SearchBar } from 'react-native-elements';
import { FlatList } from 'react-native-gesture-handler';
class Main extends Component {
constructor(props) {
super(props);
this.state = { search: '', data: [] };
}
componentDidMount() {
fetch('https://developers.zomato.com/api/v2.1/search', {
method: 'GET',
headers: {
'user-key': '999999999999999999999999999'
},
params: JSON.stringify({
entity_type: 'city',
q: {this.state.search}
}),
}).then((response) => response.json())
.then((responseJson) => { return this.setState({ data: responseJson.restaurants }) })
.catch((error) => { console.warn(error) }
);
}
render() {
let data = this.state.data;
let name = data.map(p => p.restaurant.name)
console.warn("Check Data", name)
return (
<View>
<SearchBar
round
searchIcon={{ size: 24 }}
placeholder='Search'
onChangeText={search => { this.setState({ search }) }}
value={this.state.search}
/>
//Using this method to display the data if any
{name.length != 0 ?
<FlatList
data={name}
keyExtractor={(x, i) => x + i}
renderItem={({ name }) => <Text>{name}-DATA</Text>}
/>
: <View style={{height:"100%", width:"100%", alignItems:"center",
justifyContent:"center"}}>
<Text>No data found</Text>
</View>
}
</View>
);
}
}
export default Main;
Maybe the way I declared state is wrong, or maybe the way I'm storing the data in the state is wrong.
I got the names of the restaurant in the console.warn successfully.
Without your users-key I can't surely understand what is your api results.
Here
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { SearchBar } from 'react-native-elements';
import { FlatList } from 'react-native-gesture-handler';
class Main extends Component {
constructor(props) {
super(props);
this.state = { search: '', data: [] };
}
componentDidMount() {
fetch('http://phplaravel-325095-1114213.cloudwaysapps.com/api/shop/shop/', {
method: 'GET',
}).then((response) => response.json())
.then((responseJson) => { return this.setState({ data: responseJson }) })
.catch((error) => { alert(error) }
);
}
render() {
let data = this.state.data;
return (
<View>
<SearchBar
round
searchIcon={{ size: 24 }}
placeholder='Search'
onChangeText={search => { this.setState({ search }) }}
value={this.state.search}
/>
{data.length != 0 ?
<FlatList
data={data}
keyExtractor={(x, i) => x + i}
renderItem={({ item }) => <Text>{item.name}-DATA</Text>}
/>
: <View style={{height:"100%", width:"100%", alignItems:"center",
justifyContent:"center"}}>
<Text>No data found</Text>
</View>
}
</View>
);
}
}
export default Main;
This is a working code with another api call just add your api call instead on mine.. This is working properly. I guess you are just messing with your data.
Try replacing the renderItem from FlatList to
renderItem={({ item }) => <Text>{item}-DATA</Text>}
Also, replace the condition to use double equals like name.length !== 0
Check the url link properly.
https://developers.zomato.com/api/v2.1/search/999999999999999999999999999
Just check it on web browser it is showing message : The requested url was not found
It means we are not getting any data from this URL.
That why we are not able to map any data.
I'm pulling data from the database, but I'm getting SyntaxError: Unexpected EOF React Native error when pulling data. Where's the problem?
class App extends Component {
fetch('http://..../tbl_menuler_tipsiparis.php')
.then((response) => response.json())
.then((responseJson) => {
firebase.database().ref('/TBL_SIPARISLER/tip').set(responseJson);
})
.catch((error) => {
console.error(error);
});
}
learn react State and Lifecycle
for your code
import React, { Component } from 'react';
import { Text, View } from 'react-native';
export default class componentName extends Component {
constructor(props) {
super(props);
this.fetchDataWithFetchAPI();
}
fetchDataWithFetchAPI = () => {
fetch('http://..../tbl_menuler_tipsiparis.php')
.then((response) => response.json())
.then((responseJson) => {
firebase.database().ref('/TBL_SIPARISLER/tip').set(responseJson);
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<View>
<Text>{"SampleText"}</Text>
</View>
);
}
}
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>