https://codesandbox.io/s/currying-voice-toq9t - I am trying to save the json object into the component state, then render the name into the browser.
getProfile() {
axios
.get(
"https://cors-anywhere.herokuapp.com/" +
"https://phantombuster.s3.amazonaws.com....."
)
.then(response => {
this.setState({
profile: {
name: response.data.name
}
});
})
.catch(error => this.setState({ error, isLoading: false }));
}
Your Response data is an array form so,You need to give Index.I hope it will helps you.
getProfile() {
axios
.get(
"https://cors-anywhere.herokuapp.com/" +
"https://phantombuster.s3.amazonaws.com/YRrbtT9qhg0/NISgcRm5hpqtvPF8I0tLkQ/result.json"
)
.then(response => {
this.setState({
profile: {
name: response.data[0].name
}
});
})
.catch(error => this.setState({ error, isLoading: false }));
}
The response.data is an array where in first position there is the information that you are looking for, so the setState should be like this:
this.setState({
profile: {
name: response.data[0].name
}
});
or
const [obj] = response.data;
this.setState({
profile: {
name: obj.name
}
});
Your response.data returns an array.so you need to traverse it inside a loop.
import React from "react";
import ReactDOM from "react-dom";
import axios from "axios";
export class Profile extends React.Component {
constructor(props) {
super(props);
this.state = { profile: [] };
}
componentDidMount() {
this.getProfile();
}
getProfile() {
axios
.get(
"https://cors-anywhere.herokuapp.com/" +
"https://phantombuster.s3.amazonaws.com/YRrbtT9qhg0/NISgcRm5hpqtvPF8I0tLkQ/result.json"
)
.then(response => {
console.log("response: ", response)
this.setState({
profile: response.data
});
})
.catch(error => this.setState({ error, isLoading: false }));
}
render() {
let { name } = this.state.profile;
const { error } = this.state;
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Profile</h1>
{error ? <p>{error.message}</p> : null}
</header>
<div className="App-feeds" />
<div className="panel-list">
{this.state.profile.map((element) => <p>First Name: {element.name}</p>)}
</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Profile />, rootElement);
Related
I have created a Banner Component in React Native and now im trying to add data from a function (seperate .js file) in this component. I want to fetch the data on the inital load from my Home Screen but i dont know how to pass the data from my function. I hope you can help me.
This is my code:
home.js
export function HomeScreen() {
{/*This will cause an error*/}
const [item, setItem] = React.useState([]);
React.useEffect(() => {
{/*Function where i fetch my Data from API */}
getbannerdata().then(res => {
setItem(res)
})
console.log(item)
}, [])
return (
<SafeAreaProvider>
<SafeAreaView style={style.container}>
<View>
{/*Banner Component with Data param*/}
<Banner data={item} />
<Text>Home</Text>
</View>
</SafeAreaView>
</SafeAreaProvider>
);
}
My function:
bannerdata.js
export const getbannerdata = () => {
const [data, setData] = React.useState([])
console.log('Test')
fetch('http://192.168.178.46:8000/intranet/messages/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then(res => res.json())
.then(res => {
console.log(res)
setData(res)
})
.catch(error => console.log(error));
return data;
};
I hope you can help me.
You should use useState in your component only not in the function where you fetch data.
bannerdata.js
export const getbannerdata = () => {
return fetch('http://192.168.178.46:8000/intranet/messages/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
};
home.js
import { getbannerdata } from './bannerdata'; //import getbannerdata function and you should provide the path of bannerdata.js
export function HomeScreen() {
const [item, setItem] = React.useState([]);
React.useEffect(() => {
{/*Function where i fetch my Data from API */}
getbannerdata()
.then(res => res.json())
.then(res => {
console.log(res)
setItem(res);
});
.catch(error => console.log(error));
}, []);
return (
<SafeAreaProvider>
<SafeAreaView style={style.container}>
<View>
{/*Banner Component with Data param*/}
<Banner data={item} />
<Text>Home</Text>
</View>
</SafeAreaView>
</SafeAreaProvider>
);
}
Thank you for your help.
This is my final solution.
Its a little bit different but now it works as expected
bannerdata.js
import * as React from 'react';
function getbannerdata(){
return fetch ('http://192.168.178.46:8000/intranet/messages/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then((res) => res.json())
.then((resData) => {
return resData;
})
.catch(error => console.log(error))
};
export { getbannerdata }
home.js
import {getbannerdata} from './home/bannerdata.js';
export function HomeScreen() {
const [item, setItem] = React.useState([]);
React.useEffect(() => {
getbannerdata()
.then(res => setItem(res))
}, []);
return (
<SafeAreaProvider>
<SafeAreaView style={style.container}>
<View>
{/*Banner Component with Data param*/}
<Banner data={item} />
<Text>Home</Text>
</View>
</SafeAreaView>
</SafeAreaProvider>
);
}
I am trying to filter search my API data in react.js but I'm getting this error, cannot read property 'filter' of undefined. This is my JSON data link: https://alert-amigo-api.herokuapp.com/products/
Since the JSON data returns an array of objects, I have declared that in the props and used the same. What is the problem?
import FilterResults from 'react-filter-search';
import React, { Component } from "react";
class UserProfile extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
products: [],
value: ''
};
}
componentWillMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(
(result) => {
this.setState({
isLoaded: true,
products: result.products
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
console.log(this.state.products[0]);
}
handleChange = event => {
const { value } = event.target;
this.setState({ value });
};
render() {
const { error, isLoaded, products, value } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="content-margin">
<input type="text" value={value} onChange={this.handleChange} />
<FilterResults
value={value}
products={products}
renderResults={products => (
<div>
{products.map(el => (
<div>
<span>{el.productName}</span>
</div>
))}
</div>
)}
/>
</div>
);
}
}
}
export default UserProfile;
By testing that exact example, you will notice that the fetch URL does not return products:
fetch('https://jsonplaceholder.typicode.com/users')
The URL should be:
fetch('https://alert-amigo-api.herokuapp.com/products/')
Now result.products does contain an array. I suggest slightly bullet-proofing your code:
(result) => {
this.setState({
isLoaded: true,
products: result.products || [] // <-- add empty array
});
Or, if you prefer, on the render method:
render() {
{ products &&
<FilterResults ... />
}
}
i am trying to parse a json file by displaying all the names in the clubs
the json file is https://raw.githubusercontent.com/openfootball/football.json/master/2017-18/it.1.clubs.json
my current code i have is
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: null,
}
}
componentDidMount() {
return fetch('https://raw.githubusercontent.com/openfootball/football.json/master/2017-18/it.1.clubs.json')
.then ( (response) => response.json() )
.then ( (responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.clubs,
})
})
.catch((error) => {
console.log(error)
});
}
render() {
if (this.state.isLoading) {
return (
<View style = {styles.containter}>
<ActivityIndicator/>
</View>
)
} else {
return (
<View>
<Text>{this.state.dataSource.name}</Text>
</View>
)
I just want to loop through to display all the names in the clubs
Try this:
Couple of edits: Changing the initial state of dataSouce value as an array, this is to ensure it doesn't throw can't read property map of undefined.
You don't need to return the fetch call, because you don't need a promise to returned.
EDIT: Added a loading text before all the clubs are loaded.
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
state = {
isLoading: false,
dataSource: []
};
componentDidMount() {
this.setState({ isLoading: true }, () => {
fetch(
"https://raw.githubusercontent.com/openfootball/football.json/master/2017-18/it.1.clubs.json"
)
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
this.setState({
isLoading: false,
dataSource: responseJson.clubs
});
})
.catch(error => {
this.setState({ loading: false });
console.log(error);
});
});
}
render() {
return (
<div className="App">
<h1>Club Names</h1>
{this.state.isLoading ? (
<h1>Loading Clubs...</h1>
) : (
this.state.dataSource.map(data => <h2 key={data.key}>{data.name}</h2>)
)}
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Sandbox Link: https://codesandbox.io/s/throbbing-dream-7lpcm?fontsize=14
Trying to fetch some json from the following url: https://talaikis.com/api/quotes/random/
I'm using an activity indicator while waiting for the json to be fetched. That apparently never happens and so the app just displays the activity indicator. I tried using the sample that is provided in the networking tutorial in the official react native documentation
Here is the code:
import React, { Component } from 'react';
import {AppRegistry, StyleSheet, Text, View, ActivityIndicator} from 'react-native';
import Header from '../header/Header';
export default class SingleQuote extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true
}
}
loadingQuoteFromUrl(){
return fetch('https://talaikis.com/api/quotes/random/')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
render() {
var style = require("./styles.js");
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return (
<View style={style.container}>
<Header text="Daily Quote" />
<View style={style.textContainer}>
<Text
adjustsFontSizeToFit
numberOfLines={3}
style={style.textStyle}
>
{this.state.dataSource.quote}
</Text>
<Text
adjustsFontSizeToFit
numberOfLines={1}
style={style.textStyle}
>
{this.state.dataSource.author}
</Text>
</View>
</View>
);
}
}
You are not invoking loadingQuoteFromUrl anywhere in your App. For fetch operations componentDidMount is a suitable lifecycle method. So, you can use it. But first, you should bind this function in order to use this context. You can do this in the constructor or define it as an arrow function without binding.
class SingleQuote extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true
};
this.loadingQuoteFromUrl = this.loadingQuoteFromUrl.bind(this);
}
componentDidMount() {
this.loadingQuoteFromUrl();
}
loadingQuoteFromUrl() {
return fetch("https://talaikis.com/api/quotes/random/")
.then(response => response.json())
.then(responseJson => {
this.setState(
{
isLoading: false,
dataSource: responseJson
},
function() {}
);
})
.catch(error => {
console.error(error);
});
}
render() {
if (this.state.isLoading) {
return <div>Loading...</div>;
}
return (
<div>
<div>
<p>{this.state.dataSource.quote}</p>
<p>{this.state.dataSource.author}</p>
</div>
</div>
);
}
}
ReactDOM.render(<SingleQuote />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
class SingleQuote extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true
};
}
componentDidMount() {
this.loadingQuoteFromUrl();
}
loadingQuoteFromUrl = () => {
return fetch("https://talaikis.com/api/quotes/random/")
.then(response => response.json())
.then(responseJson => {
this.setState(
{
isLoading: false,
dataSource: responseJson
},
function() {}
);
})
.catch(error => {
this.setState(
{
isLoading: false,
}
console.error(error);
});
}
render() {
const { isLoading } = this.state;
const { dataSource } = this.props;
if (isLoading) {
return <div>Loading...</div>;
}
return (
<div>
<div>
<p>{dataSource.quote}</p>
<p>{dataSource.author}</p>
</div>
</div>
);
}
}
ReactDOM.render(<SingleQuote />, document.getElementById("root"));
I have created REST API endpoint i.e localhost:5000/api/match/:match_idNow I want to fetch data from this endpoint and display it on frontend but I am getting undefined error.
In server.js :
//Get a particular match stats
app.get('/api/match/:match_id', (req, res) =>{
let match = req.params.match_id;
matches.findOne({id: parseInt(match)}).then(Match =>{
res.json(Match);
});
});
In matchinfo.js :
import React, { Component } from 'react';
class Matchinfo extends Component {
constructor(props){
super(props);
this.state = {
info:[],
loading:true
};
}
componentDidMount(){
fetch('api/match/:match_id')
.then(res => res.json())
.then(res => {
console.log(res)
this.setState({
info:res,
loading:false
})
})
}
render() {
if (this.state.loading) {
return <img src="https://upload.wikimedia.org/wikipedia/commons/b/b1/Loading_icon.gif" />
}
return (
<div>
<p class="match">MATCH {info.id}</p>
<h4>{info.team1}</h4>
<p>VS</p>
<h4>{info.team2}</h4>
<div class="winner">
<h3>WINNER</h3>
<h4>{info.winner}</h4>
</div>
</div>
);
}
}
export default Matchinfo;
In matchinfo component I am getting failed to compile after loader is finished spinning see screenshot for more clarification.
JSON Response :
Try below updated code. It should work as you expected
import React, { Component } from 'react';
class Matchinfo extends Component {
constructor(props){
super(props);
this.state = {
info:[],
loading:true
};
}
componentDidMount(){
fetch('api/match/:match_id')
.then(res => res.json())
.then(res => {
console.log(res)
this.setState({
info:res,
loading:false
})
})
}
renderLoading(){
<img src="https://upload.wikimedia.org/wikipedia/commons/b/b1/Loading_icon.gif" />
}
render() {
const {info} = this.state;
return (
<div>
{this.state.loading ? this.renderLoading(): ''}
{this.state.info.length > 0 && (
<div>
<p class="match">MATCH {info.id}</p>
<h4>{info.team1}</h4>
<p>VS</p>
<h4>{info.team2}</h4>
<div class="winner">
<h3>WINNER</h3>
<h4>{info.winner}</h4>
</div>
</div>
)}
</div>
);
}
}
export default Matchinfo;