React Native Networking with react-native-router-flux - javascript

Hey guys I have a short question. I want to give every Button a other Page.
import React, { Component } from 'react';
import { ActivityIndicator, FlatList, Text, View, TouchableOpacity } from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
isLoading: true
};
}
componentDidMount() {
fetch('https://reactnative.dev/movies.json')
.then((response) => response.json())
.then((json) => {
this.setState({ data: json.movies });
})
.catch((error) => console.error(error))
.finally(() => {
this.setState({ isLoading: false });
});
}
render() {
const { data, isLoading } = this.state;
return (
<View style={{ flex: 1, padding: 24 }}>
{isLoading ? <ActivityIndicator/> : (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<TouchableOpacity>
<Text>{item.title}</Text>
</TouchableOpacity>
)}
/>
)}
</View>
);
}
};
The Code give me the movie names as Button and I can click on everyone. Right now I want to open for every Button a other page with react-native-router-flux.
{
"title": "The Basics - Networking",
"description": "Your app fetched this from a remote endpoint!",
"movies": [
{
"id": "1",
"title": "Star Wars",
"releaseYear": "1977"
},
{
"id": "2",
"title": "Back to the Future",
"releaseYear": "1985"
},
{
"id": "3",
"title": "The Matrix",
"releaseYear": "1999"
},
{
"id": "4",
"title": "Inception",
"releaseYear": "2010"
},
{
"id": "5",
"title": "Interstellar",
"releaseYear": "2014"
}
]
}
This is the Json Data where I fetch the names. Maybe the "id" will help me, but I really dont know what can I right now do.

I can only give you some recommend, because it is too rough to explain although is is a short question.
I remember using react-native-router-flux have to import your scene(page) and using Actions.somepage() to route to the page. But using FlastList is hard to Actions.eachpage like this. (Maybe just my skills are not good enough to achieve)
If you want to achieve like your description, I will recommend you to create a new page component to handle all of the scene now we just called "HandlePage", and then you could add it to your TouchableOpacity by using like
import HandlePage from "./HandlePage";
...
<TouchableOpacity onPress={() => { Actions.HandlePage({page: item.id}); }}
So that you could control the page at HandlePage , take this parameter(id) to handle which page you want to render. Actually, is only using one Actions.HandlePage to route but have more flexible to render what you want.
Hope it could help.
Update:
Something like:
import StarWars from "./StarWars";
import TheMatrix from "./TheMatrix";
import Inception from "./Inception";
import Interstellar from "./Interstellar";
export default class HandlePage extends React.Component {
checkSwitch = param => {
switch (param) {
case "1":
return <StarWars/> ;
case "2":
return <TheMatrix recordCount = {this.state.recordCount}/>;
case "3":
return <Inception disabled = {this.state.disabled3}/>;
case "4":
return <Interstellar alert = {this.state.alert4}/>;
default:
return null;
}
};
render() {
return ({
this.checkSwitch(this.props.page)
})
}
}

Related

How to get all JSON data inside the brackets using fetch?

I am newbie to react native and I would like to create a simple app to fetch JSON data.
Here is my json file.
[
{
"fruit": "Apple",
"size": "Large",
"color": "Red"
},
{
"fruit": "Orange",
"size": "big",
"color": "Orange"
}
]
Here is my react native code
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { data: '' };
}
componentDidMount = () => {
fetch('https://othersite.my.json', {
method: 'GET'
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
data: responseJson
})
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<View style={styles.container}>
<Text>
{this.state.data}
//for debug {this.state.data.fruit}
</Text>
</View>
);
}
}
But it doesn't work.
Your fetch looks good in there. Considering you are able to fetch data from the API and set the state. You can use map() function to display your data
render(){
return (
<View style={styles.container}>
{this.state.data.map((item) => {
console.log(item.fruit)
console.log(item.size)
console.log(item.color)
})
</View>
);
}
If the json file is inside your react project, you can import the like this:
const fruits = require('path/to/json/my.json');
console.log(fruits[0].size);

React Router passing data from one component to another

So I have a problem with passing data from one Component to another. So I have Free To Play Component which has is taking freetoplay array from json and displaying it. I have also a Link which should open up a Payment Route and pass the data, In the Payment I have a filter function, which is fitering objects based on their id, Anyway when I press on the Link, it should display the image class and price, but it does not, I dont know why. If anyone could help me I would be very grateful. Cheers
import React from 'react'
import { useParams, Link } from "react-router-dom";
import data from "../data.json";
function Payment() {
const { productId } = useParams();
const filteredData = data.filter((product) => product.id === productId)[0];
return (
<div className='Payment'>
<img src={filteredData.image}></img>
<h1>{filteredData.price}</h1>
<h1>{filteredData.name}</h1>
</div>
)
}
export default Payment
import React from 'react'
import data from "./data.json";
import {
Link
} from "react-router-dom";
import { SearchContext } from './SearchContext';
function FreeToPlay() {
const {filterProduct}=React.useContext(SearchContext);
return (
<>
<div className='All' >
{data[0].freetoplay.filter(filterProduct).map((product) => {
return (
<div className='f2p' key={product.id}>
<img src={product.image}></img>
<h2>{product.name}</h2>
<h5>{product.price}</h5>
<Link
to={`/payment/${product.id}`}
className='link'
>
Buy Now
</Link>
</div>
);
})}
</div>
</>
);
}
export default FreeToPlay
json
[
{
"freetoplay": [{
"id": "0",
"image": "src=fsdf",
"price": "60$",
"name": "CS Go"
},
{
"id": "1",
"image": "src=fsdf",
"price": "6$",
"name": "Fifa"
}
],
"action": [{
"id": "2",
"image": "src=fsdf",
"price": "60$",
"name": "doom"
},
{
"id": "3",
"image": "src=fsdf",
"price": "66$",
"name": "cyberpunk"
}
],
}
]
this is the Route
<Route path="/payment/:productId">
<Payment/>
</Route>
It looks like your issue might be in the handling of your data.filter in the Payment component.
You use:
const filteredData = data.filter((product) => product.id === productId)[0];
But your data imported from data.json is an object, not an array.
You must have meant either:
const filteredData = data.action.filter((product) => product.id === productId)[0];
Or:
const filteredData = data.freetoplay.filter((product) => product.id === productId)[0];

mapping through array of objects

I am trying to map through the following data and return "Balance" but it keeps telling me that "coding" its undefined.
here its the array
"entry": [
{
"resource": {
"id": "1980438",
"type": {
"coding": [
{
"system": "https://www.medeo-health.com/uploads/1/1/8/1/118121028/s491564155970805143-c3-i1-w640_orig.jpeg",
"code": "25062444",
"display": "Balance"
}
]
},
"manufactureDate": "2017-01-08",
"expirationDate": "2020-01-08",
"owner": {
"reference": "Organization/1980437"
}
},
"search": {
"mode": "match"
}
}, ...
this is what I am trying:
import React, { Component } from 'react';
import Device from './Device/Device';
import axios from 'axios';
class Devices extends Component {
state = {
devices: null
}
componentDidMount() {
axios.get('http://hapi.fhir.org/baseDstu3/Device?organization=1980437&_include=Device:organization&_sort=device-name')
.then(res => {
this.setState({ devices: res.data.entry });
})
.catch(error => {
console.log(error);
})
}
render() {
let devices = <p style={{ textAlign: "left", margin: "0" }}>This practitioner have no devices!</p>;
if (this.state.devices) {
devices = this.state.devices.map(device => {
return (
<Device
key={device.resource.id}
name={device.resource.type.coding[0].display}
/>
)
});
}
return (
<div>
{devices}
</div>
);
};
};
export default Devices;
the id returns well but for name it keeps getting "Cannot read property 'coding' of undefined"
what I am doing wrong?
Got the Issue. You are getting undefined because the last object you are receiving does not contain a type property in it. Please Check
Try Something Like this
{this.state.devices.map(device => {
if (device.resource.type) { //check type property exists first then render
console.log(device.resource.type.coding[0].display);
return (
<p key={device.resource.id}>
{device.resource.type.coding[0].display}
</p>
);
} else return null;
})}

Getting error Invariant Violation tried to get frame out of range index?

I have create VenueList component. I want to display list using FlatList component in react native app. I am getting error: Invariant Violation tried to get frame out of range index (See screenshot).
Code:
VenueList.js:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { View, Text, FlatList, StyleSheet } from 'react-native';
import { connect } from 'react-redux';
import { fetchVenues } from '../actions/venueAction';
class VenueList extends Component {
componentWillMount () {
this.props.fetchVenues();
}
renderItem = ({ item }) => (
<View style={styles.item}>
<Text>{item.attributes.name}</Text>
</View>
);
render() {
return (
<FlatList
styles={styles.container}
data={this.props.venues}
renderItem={this.renderItem}
/>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
item: {
padding: 16,
borderBottomWidth: 1,
borderBottomColor: '#ccc'
}
});
VenueList.propTypes = {
fetchVenues: PropTypes.func.isRequired,
venues: PropTypes.array.isRequired
}
const mapStateToProps = state => ({
venues: state.venues.items
})
export default connect (mapStateToProps, { fetchVenues })(VenueList);
venueReducer.js:
import { FETCH_VENUES } from '../actions/types';
const initialState = {
items: []
}
export default function (state = initialState, action) {
switch (action.type) {
case FETCH_VENUES:
return {
...state,
items: action.payload
};
default:
return state;
}
}
venueAction.js:
import { FETCH_VENUES } from './types';
import axios from 'axios';
export const fetchVenues = () => dispatch => {
axios.get(`my_api_link`)
.then( venues =>
dispatch({
type: FETCH_VENUES,
payload: venues
})
)
.catch( error => {
console.log(error);
});
};
The data which I want to display from API endpoint has json data as follows:
{
"data": [
{
"type": "venues",
"id": "nb",
"attributes": {
"name": "Barasti Beach",
"description": "Barasti Beach is lotacated in the awesome barasti beach",
"price_range": "$$$",
"opening_hours": "10:30-12:40/16:00-2:00",
"organization": {
"id": "GD",
"legal_name": "Barasti",
"brand": "Barasti"
},
"place": {
"address": "Le Meridien Mina Seyahi Beach Resort & Marina, Dubai Marina - Dubai - United Arab Emirates",
"latitude": "25.092648",
"location": [
"Marina Bay",
"Dubai",
"Arab Emirate United"
]
}
}
}
],
"meta": {
"total": 1,
"cursor": {
"current": 1,
"prev": null,
"next": null,
"count": 25
}
}
}
See screenshot:
As per the the above response for the api request,
The problem is with the payload which is set in the actions. You need to pass the data from the api to the Flatlist since it accepts only arrays.
axios.get(`my_api_link`)
.then( venues =>
dispatch({
type: FETCH_VENUES,
payload: venues.data
})
)
EDIT:
Adding in VenueList.js component (if the api is returning values inside data key):
renderItem = ({ item }) => (
<View style={styles.item}>
<Text>{item.attributes.name}</Text>
</View>
);
render() {
return (
<FlatList
styles={styles.container}
data={this.props.venues.data}
renderItem={this.renderItem}
/>
);
}

ReactJS mapping to API

import React, { Component } from 'react';
import axios from 'axios';
class Meetups extends Component {
constructor(props) {
super(props);
console.log('in constructor');
this.state = {
results: [],
};
}
componentDidMount() {
console.log('meetup feed');
axios.get('https://api.meetup.com/2/categories?offset=0&format=json&photo-host=public&page=20&order=shortname&desc=false&sig_id=211627025&sig=ae69aec13f23c7837cd55c5a68b99e00719fa225')
//response
.then(response => response.json())
.then(data => this.setState({results:data.results}));
}
render() {
const {results} =this.state;
return(
<div>
{results.map(result =>
<div key={result.id} className='container'>
{result.name}
</div>
)}
</div>
);
}
}
export default Meetups;
JSON format which I'm receiving:
{
"results": [
{
"name": "Arts & Culture",
"sort_name": "Arts & Culture",
"id": 1,
"shortname": "Arts"
},
{
"name": "Book Clubs",
"sort_name": "Book Clubs",
"id": 18,
"shortname": "Book Clubs"
},
{
"name": "Career & Business",
"sort_name": "Career & Business",
"id": 2,
"shortname": "Business"
}
]
}
I am trying to use Meetup API in my project. But could not able to connect with it. There might be a problem with mapping. I want to know exact mapping for the given json format. Please help me out. Thanks
import React, { Component } from 'react';
import axios from 'axios';
class Meetups extends Component {
state = {
results: []
}
componentDidMount() {
axios.get('https://api.meetup.com/2/categories?offset=0&format=json&photo-host=public&page=20&order=shortname&desc=false&sig_id=211627025&sig=ae69aec13f23c7837cd55c5a68b99e00719fa225')
.then(response => {
let results = response.data.results;
this.setState({ results: results });
console.log(response);
})
}
render() {
let studentsDisplay = (
this.state.results.map( (result, index) =>
<div key={index} className="card" style= { {width: '18rem'} }>
{result.name}
<br/>
{result.shortname}
</div>
));
return (
<div className='container'>
{
studentsDisplay
}
</div>
);
}
}
export default Meetups;

Categories

Resources