.map() only displaying the last item from array - json

I want to use the Citybik.es API (http://api.citybik.es/) to show data on a Leaflet map.
At the moment, the code is only showing the last item from the bikeData.map(), inside the render function.
The console.log(data) is showing every iterated item from the bikeData.map(), but only displaying the last item.
I am looking for something like this.
What am I missing?
The response looks something like this:
{
"networks": [
{
"company": [
"Bike U Sp. z o.o."
],
"href": "/v2/networks/bbbike",
"id": "bbbike",
"location": {
"city": "Bielsko-Bia\u0142a",
"country": "PL",
"latitude": 49.8225,
"longitude": 19.044444
},
"name": "BBBike"
},
{
"company": [
"PBSC",
"Alta Bicycle Share, Inc"
],
"href": "/v2/networks/melbourne-bike-share",
"id": "melbourne-bike-share",
"location": {
"city": "Melbourne",
"country": "AU",
"latitude": -37.814107,
"longitude": 144.96328
},
"name": "Melbourne Bike Share"
}
}
Here's the JavaScript:
import React, { Component } from 'react';
import L from 'leaflet';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
// code for map marker icon
var myIcon = L.icon({
iconUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAApCAYAAADAk4LOAAAFgUlEQVR4Aa1XA5BjWRTN2oW17d3YaZtr2962HUzbDNpjszW24mRt28p47v7zq/bXZtrp/lWnXr337j3nPCe85NcypgSFdugCpW5YoDAMRaIMqRi6aKq5E3YqDQO3qAwjVWrD8Ncq/RBpykd8oZUb/kaJutow8r1aP9II0WmLKLIsJyv1w/kqw9Ch2MYdB++12Onxee/QMwvf4/Dk/Lfp/i4nxTXtOoQ4pW5Aj7wpici1A9erdAN2OH64x8OSP9j3Ft3b7aWkTg/Fm91siTra0f9on5sQr9INejH6CUUUpavjFNq1B+Oadhxmnfa8RfEmN8VNAsQhPqF55xHkMzz3jSmChWU6f7/XZKNH+9+hBLOHYozuKQPxyMPUKkrX/K0uWnfFaJGS1QPRtZsOPtr3NsW0uyh6NNCOkU3Yz+bXbT3I8G3xE5EXLXtCXbbqwCO9zPQYPRTZ5vIDXD7U+w7rFDEoUUf7ibHIR4y6bLVPXrz8JVZEql13trxwue/uDivd3fkWRbS6/IA2bID4uk0UpF1N8qLlbBlXs4Ee7HLTfV1j54APvODnSfOWBqtKVvjgLKzF5YdEk5ewRkGlK0i33Eofffc7HT56jD7/6U+qH3Cx7SBLNntH5YIPvODnyfIXZYRVDPqgHtLs5ABHD3YzLuespb7t79FY34DjMwrVrcTuwlT55YMPvOBnRrJ4VXTdNnYug5ucHLBjEpt30701A3Ts+HEa73u6dT3FNWwflY86eMHPk+Yu+i6pzUpRrW7SNDg5JHR4KapmM5Wv2E8Tfcb1HoqqHMHU+uWDD7zg54mz5/2BSnizi9T1Dg4QQXLToGNCkb6tb1NU+QAlGr1++eADrzhn/u8Q2YZhQVlZ5+CAOtqfbhmaUCS1ezNFVm2imDbPmPng5wmz+gwh+oHDce0eUtQ6OGDIyR0uUhUsoO3vfDmmgOezH0mZN59x7MBi++WDL1g/eEiU3avlidO671bkLfwbw5XV2P8Pzo0ydy4t2/0eu33xYSOMOD8hTf4CrBtGMSoXfPLchX+J0ruSePw3LZeK0juPJbYzrhkH0io7B3k164hiGvawhOKMLkrQLyVpZg8rHFW7E2uHOL888IBPlNZ1FPzstSJM694fWr6RwpvcJK60+0HCILTBzZLFNdtAzJaohze60T8qBzyh5ZuOg5e7uwQppofEmf2++DYvmySqGBuKaicF1blQjhuHdvCIMvp8whTTfZzI7RldpwtSzL+F1+wkdZ2TBOW2gIF88PBTzD/gpeREAMEbxnJcaJHNHrpzji0gQCS6hdkEeYt9DF/2qPcEC8RM28Hwmr3sdNyht00byAut2k3gufWNtgtOEOFGUwcXWNDbdNbpgBGxEvKkOQsxivJx33iow0Vw5S6SVTrpVq11ysA2Rp7gTfPfktc6zhtXBBC+adRLshf6sG2RfHPZ5EAc4sVZ83yCN00Fk/4kggu40ZTvIEm5g24qtU4KjBrx/BTTH8ifVASAG7gKrnWxJDcU7x8X6Ecczhm3o6YicvsLXWfh3Ch1W0k8x0nXF+0fFxgt4phz8QvypiwCCFKMqXCnqXExjq10beH+UUA7+nG6mdG/Pu0f3LgFcGrl2s0kNNjpmoJ9o4B29CMO8dMT4Q5ox8uitF6fqsrJOr8qnwNbRzv6hSnG5wP+64C7h9lp30hKNtKdWjtdkbuPA19nJ7Tz3zR/ibgARbhb4AlhavcBebmTHcFl2fvYEnW0ox9xMxKBS8btJ+KiEbq9zA4RthQXDhPa0T9TEe69gWupwc6uBUphquXgf+/FrIjweHQS4/pduMe5ERUMHUd9xv8ZR98CxkS4F2n3EUrUZ10EYNw7BWm9x1GiPssi3GgiGRDKWRYZfXlON+dfNbM+GgIwYdwAAAAASUVORK5CYII=',
iconSize: [25, 41],
iconAnchor: [12.5, 41],
popupAnchor: [0, -41]
});
class App extends Component {
state = {
location: {
lat: 51.505,
lng: -0.09,
},
bikeData: [],
zoom: 2,
}
//lifecycle method to get the bike information
componentDidMount() {
fetch('https://api.citybik.es/v2/networks')
.then(res => res.json())
.then(response => {
const networkData = response.networks;
networkData.map((data) => {
console.log(data)
this.setState({
bikeData: [data]
});
})
})
}
render() {
const position = [this.state.location.lat, this.state.location.lng]
const bikeData = this.state.bikeData;
return (
<Map className="map" center={position} zoom={this.state.zoom}>
<TileLayer
attribution="&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors"
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{
bikeData && bikeData.map((data) => {
console.log(data)
return (
<Marker
icon={myIcon}
key={data.id}
position={[data.location.latitude, data.location.longitude]}>
<Popup>
Name: {data.name} <br />
Station Details: {[data.location.city, data.location.country]}
</Popup>
</Marker>
)
})
}
</Map>
)
}
}
ReactDOM.render(<App/>,
document.getElementById('root')
);

You're repeatedly overwriting the bikeData state item:
fetch('https://api.citybik.es/v2/networks')
.then(res => res.json())
.then(response => {
const networkData = response.networks;
networkData.map((data) => {
console.log(data)
this.setState({ // ***
bikeData: [data] // *** Here
}); // ***
})
})
It's not clear why you're using map there at all; certainly, map is the wrong tool if you're not going to return a value from the callback and not going to use the array map creates.
I can't say for sure, but it seems like you just want to use networkData directly:
fetch('https://api.citybik.es/v2/networks')
.then(res => res.json())
.then(response => {
const networkData = response.networks;
this.setState({bikeData: networkData});
})
Note that I'm assuming you want to overwrite bikeData with the result, not add to it.
Or if you want to transform that data in some way, you'd use the result of map:
fetch('https://api.citybik.es/v2/networks')
.then(res => res.json())
.then(response => {
const networkData = response.networks;
this.setState({
bikeData: networkData.map((data) => {
return /*...do something to data...*/;
})
});
})
(Same assumption.)
To add to bikeData, you'd need to use the callback form of setState:
this.setState(({bikeData}) => ({
bikeData: [...bikeData, ...networkData.map((data) => {
return /*...do something to data...*/;
})]
});
Also note that you have an error in your fetch call (you're not alone, a lot of people do this, so many I wrote it up on my anemic little blog): You haven't checked res.ok:
fetch('https://api.citybik.es/v2/networks')
.then(res => { // ***
if (!res.ok) { // ***
throw new Error(res.status); // ***
} // ***
}) // ***
.then(res => res.json())
.then(response => {
// ...

Try this:
componentDidMount() {
fetch('https://api.citybik.es/v2/networks')
.then(res => res.json())
.then(response => {
const networkData = response.networks; //which is currently an array
this.setState({
bikeData: networkData
});
})
}

You are not recommended to do setState inside loop. So do setState outside the loop. Also the way you push data into array isn't correct. Try below solution
const bikeDataArray = this.state.bikeData;
networkData.map(data => {
console.log(data)
bikeDataArray.push(data);
})
this.setState({
bikeData: bikeDataArray
});

Related

Fetch post API returning empty array in react native iphone app but working well in postman

I have a fetch API to get values from mysql database.Below is my screen code in which I need to get data from API:
TargetSetUpPage.js:
import React, {
useState,
useEffect,
useReducer,
useSelector,
Component,
} from "react";
import { StyleSheet, Text, Button, TextInput, ScrollView } from "react-native";
import * as authActions from "../../store/actions/auth";
const TargetSetUpPage = (props) => {
const [targetid, setTargetId] = React.useState("");
const onScreenLoad = () => {
let action;
action = authActions.getDeviceInfo();
};
useEffect(() => {
onScreenLoad();
});
return (
<ScrollView showsVerticalScrollIndicator={true}>
<Text style={styles.headingTitle}>
Set your target and start running:
</Text>
<Text style={styles.textstyle}>Target ID</Text>
<TextInput
style={styles.input}
value={targetid}
onChangeText={(targetid) => setTargetId(targetid)}
></TextInput>
<Button
title="Add"
// onPress = {() => }
/>
</ScrollView>
);
};
const styles = StyleSheet.create({
input: {
height: 40,
width: "80%",
margin: 12,
borderWidth: 1,
padding: 10,
},
headingTitle: {
fontSize: 30,
},
textstyle: {
paddingTop: 10,
fontSize: 20,
},
compact: {
flexDirection: "row",
},
buttonleft: {
paddingTop: 40,
height: 40,
width: "80%",
},
});
export default TargetSetUpPage;
Below is the store code which calls fetch API.
auth.js
import AsyncStorage from "#react-native-community/async-storage";
import Device from "../../model/Device";
export const LOGIN = "LOGIN";
export const LOGOUT = "LOGOUT";
export const GETDEVICEINFO = "GETDEVICEINFO";
export const login = (textemailid, textpassword) => {
const formData = new FormData();
formData.append("txtUemail", textemailid);
formData.append("txtUpass", textpassword);
return async (dispatch) => {
fetch("https://------------------------/login.php", {
method: "post",
body: formData,
})
.then((res) => res.text())
.then((loginresult) => {})
.catch((err) => {
console.log(err);
});
const saveDataToStorage = (loginresult) => {
AsyncStorage.setItem(
"userData",
JSON.stringify({
loginresult: loginresult,
})
);
};
dispatch({ type: LOGIN });
};
};
export const logout = () => {
return { type: LOGOUT };
};
export const getUserInfo = (textemailid) => {
const formData = new FormData();
formData.append("txtEmail", textemailid);
return async (dispatch) => {
fetch("https://------------------------/getUserInformation.php", {
method: "post",
body: formData,
})
.then((res) => res.json())
.then((getuseridresult) => {
const userid = getuseridresult.map((d) => d.id);
saveDataToStorage(userid);
})
.catch((err) => {
console.log(err);
});
const saveDataToStorage = async (userid) => {
try {
await AsyncStorage.setItem(
"userDatauserid",
JSON.stringify({
userid: userid,
})
);
} catch (e) {
alert("not saved");
}
};
};
};
export const getDeviceInfo = async () => {
const useridfordevices = await AsyncStorage.getItem("userDatauserid");
const obj = JSON.parse(useridfordevices);
const { userid } = obj;
var userid1 = userid[0];
console.log("txtUserId is " + userid1);
const formData = new FormData();
formData.append("txtUserId", userid1);
console.log(formData);
return async (dispatch) => {
fetch("https://-------------------------------/getDeviceInformation.php", {
method: "post",
body: formData,
})
.then((res) => res.json())
.then((result) => {
console.log("Hi" + result);
})
.catch((err) => {
console.log(err);
});
};
};
getDeviceInfo function in the above auth.js is not returning anything. I am sending correct data to fetch API as below:
txtUserId is 616718042ad26
FormData {
"_parts": Array [
Array [
"txtUserId",
"616718042ad26",
],
],
In postman I am getting the below JSON data:
[
{
"targetid": "TargetDevice1",
"targetname": "device_1",
"userid": "616718042ad26"
},
{
"targetid": "TargetDevice2",
"targetname": "device_2",
"userid": "616718042ad26"
}
]
Import and add dispatch in TargetSetUpPage:
TargetSetUpPage.js:
import React, {
useState,
useEffect,
useReducer,
useSelector,
Component,
} from "react";
import { StyleSheet, Text, Button, TextInput, ScrollView } from "react-
native";
import { useDispatch } from "react-redux";
import * as authActions from "../../store/actions/auth";
import AsyncStorage from '#react-native-community/async-storage';
const TargetSetUpPage = (props) => {
const [targetid, setTargetId] = React.useState("");
const dispatch = useDispatch();
const onScreenLoad = async() => {
const useridfordevices = await AsyncStorage.getItem("userDatauserid");
const obj = JSON.parse(useridfordevices);
const { userid } = obj;
var userid1 = userid[0];
console.log("txtUserId is " + userid1);
let action;
action = authActions.getDeviceInfo(
userid1
);
await dispatch(action);
};
useEffect(() => {
onScreenLoad();
});
return (
<ScrollView showsVerticalScrollIndicator={true}>
<Text style={styles.headingTitle}>
Set your target and start running:
</Text>
<Text style={styles.textstyle}>Target ID</Text>
<TextInput
style={styles.input}
value={targetid}
onChangeText={(targetid) => setTargetId(targetid)}
></TextInput>
<Button
title="Add"
// onPress = {() => }
/>
</ScrollView>
);
};
const styles = StyleSheet.create({
input: {
height: 40,
width: "80%",
margin: 12,
borderWidth: 1,
padding: 10,
},
headingTitle: {
fontSize: 30,
},
textstyle: {
paddingTop: 10,
fontSize: 20,
},
compact: {
flexDirection: "row",
},
buttonleft: {
paddingTop: 40,
height: 40,
width: "80%",
},
});
export default TargetSetUpPage;
In the store, dispatch the action to TargetSetUpPage.js from getDeviceInfo function.
auth.js:
export const getDeviceInfo = (userid1) => {
const formData = new FormData();
formData.append("txtUserId", userid1);
return async dispatch => {
fetch('https://----------/getDeviceInformation.php',
{
method:'post',
body: formData
})
.then((res) => res.json())
.then((getuserdeviceinfo) => {
const loadDevices = [];
loadDevices.push(
new Device(
getuserdeviceinfo.map((d) => d.targetid),
getuserdeviceinfo.map((d) => d.targetname),
)
);
console.log(loadDevices);
})
.catch((err) =>{
console.log(err);
})
dispatch({type:GETDEVICEINFO,availableDevice:loadDevices})
}
}
This displays the Device array from mysql database.
Array [
Device {
"TargetId": Array [
"jtgTargetDevice1",
"jtgTargetDevice2",
],
"TargetName": Array [
"device_1",
"device_2",
],
},
]

React get inner JSON object from api

Update: How do I get an array (currentSchedule) within an array (response)?
I am trying to get the JSON object in "response" within the JSON code below. For instance, I want to get the title & description in "response", but it is not returning anything for me with the codes that I implemented below.
all.json
{"responseCode":200,
"responseMessage":"Channel Listing",
"response":[{
"id":395,
"title":"Title 1",
"description":"Description 1",
"currentSchedule":[{"eventId":"123456","title":"Hello Title"]}
}]
}
App.js
class App extends Component {
constructor(props){
super(props);
this.state = {
items: [],
isLoaded: false,
}
}
componentDidMount(){
fetch('/all.json')
.then(res => {
res.json()
})
.then(json => {
this.setState({
isLoaded: true,
items: [],
})
});
}
render() {
var { isLoaded, items } = this.state;
if(!isLoaded) {
return <div>Loading...</div>;
}
else {
return (
<div className="App">
<ul>
{items.map(item => (
<li key={item.id}>
Title: {item.title} | Description: {item.description}
</li>
))};
</ul>
</div>
);
}
}
}
export default App;
You need to assign response in your setState to view it, somthing like this
componentDidMount(){
fetch('/all.json')
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json.response,
})
}).catch(console.log);
}

Populating picker in react native through fetch from the server

I am trying to get picker values from the server to my react-native project. this is my JSON data. How do I fetch it for the picker component? I tried all d methods from web results. but I get only a blank screen. Kindly please help
{
"MFBasic": {
"SkinTones": "DARK,FAIR,VFAIR",
"Build": "SLIM,ATHLETIC,PLUMPY",
"Gender": "F,M,T",
"Genre": "ACTION,COMEDY,DRAMA",
"Languages": "ENG,HINDI,TAM",
"MediaModes": "ADS,MOVIES,SHORTFILMS",
"Tags": "BIKES,HOME,JEWELLARY"
},
"Result": "Successfully Loaded MF Basic Details",
"Code": 100
}
App.js
export default class App extends Component {
state = {
PickerValueHolder:[],
Gender:'',
}
componentDidMount() {
fetch('https://movieworld.sramaswamy.com/GetMFBasicDetails.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then((response) => response.json())
.then((responseJson) => {
let PickerValueHolder = responseJson.MFBasic;
this.setState({ PickerValueHolder }); // Set the new state
}).catch((error) => {
console.error(error);
});
}
render() {
return (
<View style = {styles.MainContainer}>
{<Picker
selectedValue={this.state.Gender}
onValueChange={(itemValue, itemIndex) =>
this.setState({Gender:itemValue})} >
{ this.state.PickerValueHolder.map((item, key)=>
<Picker.Item label={item.Gender} value={item.Gender} key={key}/>
)}
</Picker>}
</View>
);
}
}
above code is my app.js file. but it returns nothing to the picker.help me please. Thank u.
Looking at the json from your API call
{
"MFBasic": {
"SkinTones": "DARK,FAIR,VFAIR",
"Build": "SLIM,ATHLETIC,PLUMPY",
"Gender": "F,M,T",
"Genre": "ACTION,COMEDY,DRAMA",
"Languages": "ENG,HINDI,TAM",
"MediaModes": "ADS,MOVIES,SHORTFILMS",
"Tags": "BIKES,HOME,JEWELLARY"
},
"Result": "Successfully Loaded MF Basic Details",
"Code": 100
}
The issue that is that you are trying to set a string where it needs an array. You can do it by doing something like this:
let genderString = responseJson.MFBasic.Gender;
let genderArray = genderString.split(',');
this.setState({ PickerValueHolder: genderArray });
let responseJson = {
"MFBasic": {
"SkinTones": "DARK,FAIR,VFAIR",
"Build": "SLIM,ATHLETIC,PLUMPY",
"Gender": "F,M,T",
"Genre": "ACTION,COMEDY,DRAMA",
"Languages": "ENG,HINDI,TAM",
"MediaModes": "ADS,MOVIES,SHORTFILMS",
"Tags": "BIKES,HOME,JEWELLARY"
},
"Result": "Successfully Loaded MF Basic Details",
"Code": 100
}
let genderString = responseJson.MFBasic.Gender;
let genderArray = genderString.split(',');
console.log(genderArray)
Because the items in your array are just strings you cannot access them by using item.Gender that won't work. You need to just access them using item.
I have created an example based on your code and implemented the change from above and fixed the Picker.Item component so it should render now. You can see the working code at the following snack https://snack.expo.io/#andypandy/picker-with-array-of-strings
import React from 'react';
import { Text, View, StyleSheet, Picker } from 'react-native';
import { Constants } from 'expo';
export default class App extends React.Component {
state = {
PickerValueHolder: [],
Gender: ''
}
componentDidMount () {
fetch('https://movieworld.sramaswamy.com/GetMFBasicDetails.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).then((response) => response.json())
.then((responseJson) => {
let genderString = responseJson.MFBasic.Gender;
let genderArray = genderString.split(',');
this.setState({ PickerValueHolder: genderArray });
}).catch((error) => {
console.error(error);
});
}
render () {
console.log(this.state.PickerValueHolder)
return (
<View style={styles.container}>
{<Picker
selectedValue={this.state.Gender}
onValueChange={(itemValue, itemIndex) =>
this.setState({ Gender: itemValue })} >
{ this.state.PickerValueHolder.map((item, key) =>
<Picker.Item label={item} value={item} key={key}/>
)}
</Picker>}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8
}
});

Is it possible to have more than one parameters in data for a FlatList?

Like this for example:
<FlatList data={ this.state.foods, this.state.trees }
renderItem={({item}) => <View><Text>{item.food}</Text><Text>{item.tree}</Text></View>
/>
As long as I have the same key (id), is it possible this can work like this?
this.state.foods:
[{
"id": "1",
"food":"chicken",
"cal":"1000",
}]
this.state.trees:
[{
"id": "1",
"tree":"pine",
"size":"10",
}]
EDIT:
render(){
const {trees, foods} = this.state
const combinedArray = trees.map(tree => Object.assign(tree, foods.find(food => food.id == tree.id)));
return(
componentDidUpdate(prevProps, prevState) {
if (!prevState.foods) {
fetch('https://www.example.com/React/food.php')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
foods: responseJson.map(item => ({ ...item, progress: new Animated.Value(0), unprogress: new Animated.Value(1) }))
}, function() {
});
})
.catch((error) => {
//console.error(error);
});
fetch('https://www.example.com/React/tree.php')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
trees: responseJson
}, function() {
});
})
.catch((error) => {
//console.error(error);
});
}
}
You need to supply a single array to a Flatlist data.
You can group the objects based on id and use them
const {trees, foods} = this.state
const combinedArray = trees.map(tree => Object.assign(tree, foods.find(food => food.id == tree.id)));
and then use combinedArray in the Flatlist
If your state is undefined or null initially then you need to add
constructor(props) {
super(props)
this.state = {
trees: [],
foods: []
}
}
to your class component.

How can I load data from a JSON file which is stored at GitHub in React Native?

I have the following JSON file in my GitHub and want to load it:
{"Cat": [
{"key": "a", "title": "Bangladesh", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/bangladesh.jpg"},
{"key": "b", "title": "Sports", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/sports.jpg"},
{"key": "c", "title": "Politics", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/politics.jpg"},
{"key": "d", "title": "Entertainment", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/entertainment.png"},
{"key": "e", "title": "Economics", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/economics.jpg"},
{"key": "f", "title": "Technology", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/technology.jpg"},
{"key": "g", "title": "Others", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/m.jpg"}
]}
I tried to use the following code to fetch it:
getMoviesFromApiAsync() {
return fetch('https://raw.githubusercontent.com/mudassir21/server/master/newsCategory.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.Cat;
})
.catch((error) => {
console.error(error);
});
}
<FlatList horizontal= {true}
data={this.getMoviesFromApiAsync()}
renderItem={({item}) => (
<TouchableOpacity
style={styles.catOption}
onPress = { ()=> this.setState({ name: item.title })}
>
<Image
style={styles.imgButton}
source={{uri: item.image}}
/>
<Text style={styles.buttonText}>{item.title}</Text>
</TouchableOpacity>
)
}
/>
However, no data is loaded from the JSON file. What's the problem?
As your fetch is triggered when the list is rendered, the result of the fetch is not set. In order to re-render the list with data I would suggest to set the result inside the state of the Component. This will trigger a re-render and you should be able to see the list after the fetch resolves:
class MyComp extends Component {
state = { result: [] }
componentWillMount(){
this.getMoviesFromApiAsync()
}
getMoviesFromApiAsync = () => fetch('https://raw.githubusercontent.com/mudassir21/server/master/newsCategory.json')
.then((response) => response.json())
.then((responseJson) => {
this.setState({ result: responseJson.Cat });
})
.catch((error) => {
console.error(error);
})
render(){
<FlatList data={this.state.result} ... />
}
}
Read this link
Use this code:
import React, { Component } from 'react';
import { ActivityIndicator, ListView, Text, View } from 'react-native';
export default class Movies extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true
}
}
componentDidMount() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson.movies),
}, function() {
// do something with new state
});
})
.catch((error) => {
console.error(error);
});
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={{flex: 1, paddingTop: 20}}>
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) => <Text>{rowData.title}, {rowData.releaseYear}</Text>}
/>
</View>
);
}
}